Last active
September 22, 2015 14:45
-
-
Save hertz1/2061277e739ffa493304 to your computer and use it in GitHub Desktop.
Implementation of python's range() function in javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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