Coded to 2010 specs (ya, it is 2016 with ES6 generators). Here's my take, with options to emulate the Python's range()
function.
Array.range = function(start, end, step){
if (start == undefined) { return [] } // "undefined" check
if ( (step === 0) ) { return []; // vs. throw TypeError("Invalid 'step' input")
} // "step" == 0 check
if (typeof start == 'number') { // number check
if (typeof end == 'undefined') { // single argument input
end = start;
start = 0;
step = 1;
}
if ((!step) || (typeof step != 'number')) {
step = end < start ? -1 : 1;
}
var length = Math.max(Math.ceil((end - start) / step), 0);
var out = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
out[idx] = start;
}
// Uncomment to check "end" in range() output, non pythonic
if ( (out[out.length-1] + step) == end ) { // "end" check
out.push(end)
}
} else {
// Historical: '&' is the 27th letter: http://nowiknow.com/and-the-27th-letter-of-the-alphabet/
// Axiom: 'a' < 'z' and 'z' < 'A'
// note: 'a' > 'A' == true ("small a > big A", try explaining it to a kid! )
var st = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&'; // axiom ordering
if (typeof end == 'undefined') { // single argument input
end = start;
start = 'a';
}
var first = st.indexOf(start);
var last = st.indexOf(end);
if ((!step) || (typeof step != 'number')) {
step = last < first ? -1 : 1;
}
if ((first == -1) || (last == -1 )) { // check 'first' & 'last'
return []
}
var length = Math.max(Math.ceil((last - first) / step), 0);
var out = Array(length);
for (var idx = 0; idx < length; idx++, first += step) {
out[idx] = st[first];
}
// Uncomment to check "end" in range() output, non pythonic
if ( (st.indexOf(out[out.length-1]) + step ) == last ) { // "end" check
out.push(end)
}
}
return out;
}
Example:
Array.range(5); // [0,1,2,3,4,5]
Array.range(4,-4,-2); // [4, 2, 0, -2, -4]
Array.range('a','d'); // ["a", "b", "c", "d"]
Array.range('B','y'); // ["B", "A", "z", "y"], different from chr() ordering
Array.range('f'); // ["a", "b", "c", "d", "e", "f"]
Array.range(-5); // [], similar to python
Array.range(-5,0) // [-5,-4-,-3-,-2,-1,0]