Last active
January 26, 2018 11:14
-
-
Save sgb-io/5be0e314442d673b872ef6ea56d936df to your computer and use it in GitHub Desktop.
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
| // 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