Skip to content

Instantly share code, notes, and snippets.

@sgb-io
Last active January 26, 2018 11:14
Show Gist options
  • Select an option

  • Save sgb-io/5be0e314442d673b872ef6ea56d936df to your computer and use it in GitHub Desktop.

Select an option

Save sgb-io/5be0e314442d673b872ef6ea56d936df to your computer and use it in GitHub Desktop.
// String.prototype.padStart + String.prototype.padEnd (ES2017)
function stringPadding(str, width, char) {
const msgs = str.split(' ')
msgs.forEach((msg) => {
const wordLength = msg.length
let totalPadding = width - wordLength
const padding = {
start: totalPadding / 2,
end: totalPadding,
}
if (totalPadding % 2 !== 0) {
const side = ['start', 'end'].find(() => (Math.random() > 0.5))
totalPadding -= 1
padding.start = totalPadding / 2
padding.end = totalPadding
padding[side] += 1
}
console.log(
msg
.padStart(padding.start + wordLength, char)
.padEnd(width, char)
)
})
}
// e.g. stringPadding('sam is my hero', 64, ':')
// -->
// ::::::::::::::::::::::::::::::sam:::::::::::::::::::::::::::::::
// :::::::::::::::::::::::::::::::is:::::::::::::::::::::::::::::::
// :::::::::::::::::::::::::::::::my:::::::::::::::::::::::::::::::
// ::::::::::::::::::::::::::::::hero::::::::::::::::::::::::::::::
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment