Skip to content

Instantly share code, notes, and snippets.

@craftgear
Last active November 25, 2017 02:52
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 craftgear/4b99435aef369ea489d438703357c5e7 to your computer and use it in GitHub Desktop.
Save craftgear/4b99435aef369ea489d438703357c5e7 to your computer and use it in GitHub Desktop.
leftPad, rightPad, oh whatever.
const pad = (leftOrRight = 'left') => maxLength => char => value => {
const strValue = typeof value === 'number' ? value.toString() : value;
if (strValue.length >= maxLength) {
return strValue;
}
if (typeof maxLength !== 'number') {
throw new Error('maxLength should be a number');
}
const padding = Array(maxLength - strValue.length)
.fill(char)
.join('');
return leftOrRight === 'left' ? `${padding}${strValue}` : `${strValue}${padding}`;
};
const leftPad = pad();
const leftPadTwo = leftPad(2);
const leftPadTwoZero = leftPadTwo('0');
const leftPadTwoSpace = leftPadTwo(' ');
console.log(leftPadTwoZero(8)); // '08'
console.log(leftPadTwoSpace(8)); // ' 8'
const rightPad = pad('right');
const rightPadFour = rightPad(4);
const rightPadFourAsterisk = rightPadFour('*');
const rightPadFourSpace = rightPadFour(' ');
console.log(rightPadFourAsterisk(8)); // '8***'
console.log(rightPadFourSpace(8)); // '8 '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment