Skip to content

Instantly share code, notes, and snippets.

@al-the-x
Last active October 24, 2016 14:57
Show Gist options
  • Save al-the-x/e8f6b9fa2ef5991ed8efbb49fc3e5dc5 to your computer and use it in GitHub Desktop.
Save al-the-x/e8f6b9fa2ef5991ed8efbb49fc3e5dc5 to your computer and use it in GitHub Desktop.
Given a string `word` of arbitrary length insert character `char` into `word` every `N` characters without modifying `word`...
func drewboyuka__breakup(s, placeholder string, n int) string {
var buf []byte
for ; len(s) > n; s = s[n:] {
buf = append(buf, s[:n]...)
buf = append(buf, placeholder...)
}
buf = append(buf, s...)
return string(buf)
}
/**
* @name {USERNAME}__breakup
*
* @param {String} word to split by {char} every {N} characters
* @param {String} char to insert into {word} every {N} characters
* @param {Number} N number of characters to insert {char} after
* @return {String}
*/
function al_the_x__breakup (word, char, N){
let n = 0, m = N;
let part, parts = [ ];
while ( part = word.slice(n,m) ){
parts.push(part);
n = m; m += N;
}
return parts.join(char);
}
function jfontanez__breakup(word, char, N){
return word
.split('')
.map((val, idx) => idx && idx % N === 0 ? `${char}${val}` : val)
.join('');
}
@al-the-x
Copy link
Author

I wanted to put this in a Tonic notebook instead, but it looks like they've changed names to RunKit instead... and forgotten my GitHub account completely. Begin unnecessarily long username recovery process!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment