Padding a string: left pad, right pad, repeating a string
This file contains 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 rep = (str, n) => { | |
if (n < 1 || !str) return ''; | |
let result = ''; | |
for (;;) { | |
if (n & 1) { | |
result += str; | |
} | |
n >>= 1; | |
if (n < 1) break; | |
str += str; | |
} | |
return result; | |
}; | |
const leftPad = (str, n, value = ' ') => rep(value, n) + str; | |
const rightPad = (str, n, value = ' ') => str + rep(value, n); | |
const padWidthLeft = (str, width, value = ' ') => | |
str.length < width ? rep(value, width - str.length) + str : str; | |
const padWidthRight = (str, width, value = ' ') => | |
str.length < width ? str + rep(value, width - str.length) : str; | |
const repeatWidthLeft = (str, width) => | |
str ? rep(str, Math.floor(width / str.length)) + str.slice(0, width % str.length) : str; | |
const repeatWidthRight = (str, width) => | |
str ? str.slice(-(width % str.length)) + rep(str, Math.floor(width / str.length)) : str; | |
console.log('**********'); | |
console.log(leftPad('abc', 7)); | |
console.log(rightPad('abc', 7)); | |
console.log(padWidthLeft('abc', 10, '-')); | |
console.log(padWidthRight('abc', 10, '-')); | |
console.log(repeatWidthLeft('abc', 10)); | |
console.log(repeatWidthRight('abc', 10)); | |
console.log(rep('*', 10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment