Skip to content

Instantly share code, notes, and snippets.

@acuppy
Last active December 20, 2015 00:09
Show Gist options
  • Save acuppy/6039328 to your computer and use it in GitHub Desktop.
Save acuppy/6039328 to your computer and use it in GitHub Desktop.
String#mapConcat: splits a string by character; iterates through each character; runs a callback on each character; and concat the callback return into a new string
String.prototype.mapConcat = (args...) ->
separator = args.slice(0,1) if $.type(args[0]) == 'string' or $.type(args[0]) == 'regexp'
separator or= ''
chars = @.split(separator)
rtn = []
for char, i in chars
rtn.push(args[0].call(@, char, i) or char)
rtn.join('')
/*
"This is my string".mapConcat(function(char, index){
if(char == 'i') return '#'
}) => "Th#s #s my str#ng"
@param String: the character itself
@param Integer: indexOf the character in the string
@return String: mutated string after concatination
*/
String.prototype.mapConcat = function() {
var args, char, chars, i, rtn, separator, _len;
args = 1 <= arguments.length ? Array.prototype.slice.call(arguments, 0) : [];
if (typeof args[0] === 'string' || (typeof (args[0]) === 'object' && args[0] instanceof RegExp)) {
separator = args.slice(0, 1);
}
separator || (separator = '');
chars = this.split(separator);
rtn = [];
for (i = 0, _len = chars.length; i < _len; i++) {
char = chars[i];
rtn.push(args[0].call(this, char, i) || char);
}
return rtn.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment