javascript convert hyphenated range to number code example

Example: javascript convert hyphenated range to number

function getNumbers(stringNumbers) {

    //personal preference, but I got this handy tip from the internet that

    //if you had assignments, better if they are individually var'ed
    var nums = [];
    var entries = stringNumbers.split(',');
    var length = entries.length;

    //for variabes that don't, comma separated
    var i, entry, low, high, range;

    for (i = 0; i < length; i++) {
        entry = entries[i];

        //shortcut for testing a -1
        if (!~entry.indexOf('-')) {
            //absence of dash, must be a number
            //force to a number using +
            nums.push(+entry);
        } else {
            //presence of dash, must be range
            range = entry.split('-');

            //force to numbers
            low = +range[0];
            high = +range[1];

            //XOR swap, no need for an additional variable. still 3 steps though
            //http://en.wikipedia.org/wiki/XOR_swap_algorithm
            if(high < low){
              low = low ^ high;
              high = low ^ high;
              low = low ^ high;
            }

            //push for every number starting from low
            while (low <= high) {
                nums.push(low++);
            }
        }
    }

    //edit to sort list at the end
    return nums.sort(function (a, b) {
        return a - b;
    });
}

Tags:

Misc Example