Last active
June 30, 2016 14:13
-
-
Save adamsilver/1ddf20d5479084d50034d9b6e66657c6 to your computer and use it in GitHub Desktop.
Reduce used for undelimit
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.unDelimit = function(delimeters) { | |
delimeters = delimeters || ["&", "="]; | |
if (delimeters.length === 1) | |
return this.split(delimeters[0]); | |
var items = this.split(delimeters[0]), | |
o = {}, | |
i = 0, | |
j = items.length, | |
subItem; | |
for (i; i<j; i++) { | |
subItem = items[i].split(delimeters[1]); | |
subItem[1] = subItem[1] || ""; | |
if (o[subItem[0]]) { | |
if (isArray(o[subItem[0]])) { | |
o[subItem[0]].push(subItem[1]); | |
} else { | |
o[subItem[0]] = [o[subItem[0]], subItem[1]]; | |
} | |
} else { | |
o[subItem[0]] = subItem[1]; | |
} | |
} | |
return o; | |
} | |
"a=1&b=2&b=3".unDelimit(['&', '=']); |
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
function undelimit(string, delimiter1, delimiter2) { | |
var parts = string.split(delimiter1); | |
return parts.reduce(function(accumulator, currentValue, index, array) { | |
var parts = currentValue.split(delimiter2); // [a, 1] | |
var key = parts[0]; | |
var value = parts[1]; | |
if(accumulator[key]) { | |
var accumulatorValue = accumulator[key]; | |
if(typeof accumulatorValue == 'string') { | |
accumulator[key] = [accumulatorValue]; | |
} | |
accumulator[key].push(value); | |
} else { | |
accumulator[key] = value; | |
} | |
return accumulator; | |
}, {}); | |
} | |
undelimit("a=1&b=2&b=3", '&', '='); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment