Skip to content

Instantly share code, notes, and snippets.

@neocotic
Last active January 19, 2021 20:19
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 neocotic/1405075 to your computer and use it in GitHub Desktop.
Save neocotic/1405075 to your computer and use it in GitHub Desktop.
JavaScript simply even padding
// JavaScript padEven
// (c) 2011 [neocotic](http://github.com/neocotic)
// Released under the MIT License
// http://en.wikipedia.org/wiki/MIT_License
function padEven(str, delim, maxLineLen) {
delim = delim || ',';
maxLineLen = maxLineLen || 80;
str = str || '';
var
arr = [],
i,
len,
limit = 0,
maxLen = 0,
padStr = ' ',
pads,
strs = str.split(delim);
for (i = 0; i < strs.length; i++) {
strs[i] = strs[i].trim();
len = strs[i].length;
if (len > maxLen) maxLen = len;
}
limit = parseInt(maxLineLen / (maxLen + delim.length + padStr.length), 10);
for (i = 0; i < strs.length; i++) {
strs[i] += delim;
pads = maxLen - strs[i].length + delim.length;
if (pads > 0) for (j = 0; j < pads; j++) strs[i] += padStr;
}
while (strs.length > 0) {
arr.push(strs.splice(0, limit).join(padStr).trim());
}
str = arr.join('\n');
return str.substring(0, str.length - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment