Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Array#pad!

My ri docco says there is an Array#pad! but runtime Ruby says there isn't. Bah. So I wrote one:

class Array
  def pad!(expected_length, pad_item = nil)
    while expected_length > length
      self << pad_item
    end
    self
  end
end

Pad //JavaScript Function



[UPDATED CODE AND HELP CAN BE FOUND HERE]



usage:

var s = "Jonas";
document.write(
  s, " => ", s.pad(20, "[]", 0), "<br />",
  s, " => ", s.pad(20, "[====]", 1), "<br />",
  s, " => ", s.pad(20, "~", 2)
);


code:

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/pad [v1.0]

String.prototype.pad = function(l, s, t){
	return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
		+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
		+ this + s.substr(0, l - t) : this;
};
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS