Last active
December 20, 2015 00:09
-
-
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
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.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 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
/* | |
"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