javascript convert hyphenated range to number

Solutions on MaxInterview for javascript convert hyphenated range to number by the best coders in the world

showing results for - "javascript convert hyphenated range to number"
Alessio
28 Sep 2017
1function getNumbers(stringNumbers) {
2
3    //personal preference, but I got this handy tip from the internet that
4
5    //if you had assignments, better if they are individually var'ed
6    var nums = [];
7    var entries = stringNumbers.split(',');
8    var length = entries.length;
9
10    //for variabes that don't, comma separated
11    var i, entry, low, high, range;
12
13    for (i = 0; i < length; i++) {
14        entry = entries[i];
15
16        //shortcut for testing a -1
17        if (!~entry.indexOf('-')) {
18            //absence of dash, must be a number
19            //force to a number using +
20            nums.push(+entry);
21        } else {
22            //presence of dash, must be range
23            range = entry.split('-');
24
25            //force to numbers
26            low = +range[0];
27            high = +range[1];
28
29            //XOR swap, no need for an additional variable. still 3 steps though
30            //http://en.wikipedia.org/wiki/XOR_swap_algorithm
31            if(high < low){
32              low = low ^ high;
33              high = low ^ high;
34              low = low ^ high;
35            }
36
37            //push for every number starting from low
38            while (low <= high) {
39                nums.push(low++);
40            }
41        }
42    }
43
44    //edit to sort list at the end
45    return nums.sort(function (a, b) {
46        return a - b;
47    });
48}