Last active
November 25, 2017 02:52
-
-
Save craftgear/4b99435aef369ea489d438703357c5e7 to your computer and use it in GitHub Desktop.
leftPad, rightPad, oh whatever.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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