Skip to content

Instantly share code, notes, and snippets.

@hertz1
Last active September 22, 2015 14:45
Show Gist options
  • Save hertz1/2061277e739ffa493304 to your computer and use it in GitHub Desktop.
Save hertz1/2061277e739ffa493304 to your computer and use it in GitHub Desktop.
Implementation of python's range() function in javascript.
/**
* Range function, similar to python's one.
* If you want to use it in for...in loops, all 4 arguments must be passed.
* @param {Number} Start - If omited, it defaults to 0.
* @param {Number} Stop
* @param {Number} Step - If omited, it defaults to 1.
* @param {Boolean} Object - If returns an object or not. Mostly used in for...in loops.
* @return {Mixed} If Object is true, returns an object, otherwise, returns an array.
*
* Examples:
* >>> range(5)
* [0, 1, 2, 3, 4]
* >>> range(1, 6)
* [1, 2, 3, 4, 5]
* >>> range(0, 30, 5)
* [0, 5, 10, 15, 20, 25]
* >>> range(0, 4, 1, true)
* {0:0, 1:1, 2:2, 3:3}
*/
function range(start, stop, step, object) {
if (stop === undefined) {
stop = start;
start = 0;
}
if (step === undefined) {
step = 1;
}
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
return [];
}
var result = object ? new Object() : new Array();
for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
object ? result[i] = i : result.push(i);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment