Skip to content

Instantly share code, notes, and snippets.

@stagas
Forked from 140bytes/LICENSE.txt
Created May 26, 2011 06:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save stagas/992678 to your computer and use it in GitHub Desktop.
Save stagas/992678 to your computer and use it in GitHub Desktop.
Padding for Strings and Numbers
function(
s, // String / Number to pad
l, // target length
c, // character used for padding
u // undefined
){
c=new Array( // reusing c to carry padding
(l= // reusing l to to carry padding length
(l||0) // target length or 0
-(''+s) // minus s.toString()
.length // .length
+1 // plus 1
)>0 // if greater than 0
&&l // return l
||0 // else don't pad
).join( // join array
c!=u // if we supplied a character
?c // the character
:' ' // else space
);
return {
l:c+s, // left padding pad().l
r:s+c, // right padding pad().r
toString:function(){ // default
return c+s // .toString()
} // behavior
}
}
var pad = function(s,l,c,u){c=new Array((l=(l||0)-(''+s).length+1)>0&&l||0).join(c!=u?c:' ');return {l:c+s,r:s+c,toString:function(){return c+s}}}
console.log(
pad(15, 5, 0).l // left padding
+ pad('foo', 5) // js does .toString()
+ pad('bar', 5, '-').r // right padding with -
)
// 00015 foobar--
function(s,l,c,u){c=new Array((l=(l||0)-(''+s).length+1)>0&&l||0).join(c!=u?c:' ');return {l:c+s,r:s+c,toString:function(){return c+s}}}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 George Stagas https://github.com/stagas
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{ "name": "pad"
, "description": "Padding for Strings and Numbers"
, "keywords":
[ "pad"
, "padding"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment