Skip to content

Instantly share code, notes, and snippets.

@freekrai
Last active March 24, 2016 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freekrai/4445a9773fc54f5170dc to your computer and use it in GitHub Desktop.
Save freekrai/4445a9773fc54f5170dc to your computer and use it in GitHub Desktop.
various utils
function leftpad (str, len, ch) {
str = String(str);
var i = -1;
if (!ch && ch !== 0) ch = ' ';
len = len - str.length;
while (++i < len) {
str = ch + str;
}
return str;
}
module.exports = leftpad;
leftpad('foo', 5) // => " foo"
leftpad('foobar', 6) // => "foobar"
leftpad(1, 2, 0) // => "01"
function rightpad (str, len, ch) {
str = String(str);
var i = -1;
if (!ch && ch !== 0) ch = ' ';
len = len - str.length;
while (++i < len) {
str += ch;
}
return str;
}
module.exports = rightpad;
rightpad('foo', 5) // => "foo "
rightpad('foobar', 6) // => "foobar"
rightpad(1, 2, 0) // => "10"
function random (max, min) {
max || (max = 999999999999);
min || (min = 0);
return min + Math.floor(Math.random() * (max - min));
}
module.exports = random;
random()
// => 519306295418
random(99) // allows specifying the max n
// => 35
random(99, 77) // => max n and min n
// => 83
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment