I would like to convert a string like "1 2 3-5"
to an array of numbers [1, 2, 3, 4, 5]
.
Following the robustness principle, the list doesn't need to be separated by spaces, comma on any other separator is accepted. The only mandatory syntax is A-B
to represent range from A
to B
(inclusive). Also, it's ok to ignore malformed input (like 1-3-5
), it can be considered "undefined behavior" as long as it doesn't raise an exception.
My current code is a follow:
function parse(string) {
let numbers = [];
for (let match of string.match(/[0-9]+(?:\-[0-9]+)?/g)) {
if (match.includes("-")) {
let [begin, end] = match.split("-");
for (let num = parseInt(begin); num <= parseInt(end); num++) {
numbers.push(num);
}
} else {
numbers.push(parseInt(match));
}
}
return numbers;
}
This seems quite convoluted for such a simple task. Is there any alternative more straightforward using "modern" Javascript (I'm targeting ES6)?
5-3
too, that provides[ 5, 4, 3 ]
\$\endgroup\$.split("-").map(Number)
and then usingMath.min()
/Math.max()
for iteration. \$\endgroup\$