I've got a simple spec for defining character sets, ranges, or wildcards. I'd like to take the string and appropriately create an array based on these rules. I have a solution but I'm sure there is a better way!
- Single characters may be used
- Sets and ranges are enclosed in brackets
[] - Sets are comma separated,
[1,3,S] - Ranges are hyphenated,
[1-3] - Sets and ranges can be combined,
[1-3,7,9-10,S] - Wildcard character is
-and not enclosed in brackets - Strings can contain the following characters are
A-Z0-9-.
Example inputs and expected outputs
'ABC'outputs['A', 'B', 'C']'S[1-2]-'outputs['S', '1-2', '-']'S[1-2]2.0[0-9][1,3,7]S'outputs['S', '1-2', '2', '.', '0', '0-9', '1,3,7', 'S']'S[1-2,7]'outputs['S', '1-2,7']
My implementation:
function stringToArray(code) {
var exploded = code.split(''),
charGroups = [],
tempGroup = '',
inGroup = false;
while (exploded.length > 0) {
var cur = exploded.shift();
if (cur === '[') {
inGroup = true;
continue;
}
if (inGroup) {
if (cur === ']') {
inGroup = false;
charGroups.push(tempGroup);
tempGroup = '';
} else {
tempGroup += cur;
}
}
if (!inGroup) {
if (cur !== ',' && cur !== '[' && cur !== ']') {
charGroups.push(cur);
}
}
}
return charGroups;
}
Demo fiddle here: http://jsfiddle.net/3q25eps3/