-
-
Save alexsandro-xpt/3243399 to your computer and use it in GitHub Desktop.
ECMAScript 5 implementation of Python's range function
This file contains 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
/** | |
* ECMAScript 5 implementation of Python's range function. | |
* @see {@link http://docs.python.org/release/1.5.1p1/tut/range.html} | |
* @param {Number} start | |
* @param {Number} end | |
* @param {Number} step | |
* @return {Array} | |
*/ | |
Object.defineProperty(Array, "range", { | |
writable: false, configurable: false, enumerable: true, | |
value: function(start, end, step) { | |
var length = start; | |
step = step === undefined? 1: step; | |
if (arguments.length == 1) { | |
start = 0; | |
} else { | |
length = Math.ceil((end-start)/step); | |
} | |
var current = start; | |
var array = (new Array(length)).join("|").split("|"); | |
return array.map(function() { | |
var value = current; | |
current += step; | |
return value; | |
}); | |
} | |
}); |
This file contains 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
console.log(Array.range(10)); | |
//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
//The given end point is never part of the generated list; Array.range(10) generates a list of 10 values, | |
//exactly the legal indices for items of a sequence of length 10. It is possible to let the range start | |
//at another number, or to specify a different increment (even negative): | |
console.log(Array.range(5, 10)) | |
//[5, 6, 7, 8, 9] | |
console.log(Array.range(0, 10, 3)) | |
//[0, 3, 6, 9] | |
console.log(Array.range(-10, -100, -30)) | |
//[-10, -40, -70] | |
//To iterate over the indices of a sequence, combine range() and the length property, as follows: | |
var a = ['Mary', 'had', 'a', 'little', 'lamb']; | |
for (var i in Array.range(a.length)) { | |
console.log(i, a[i]); | |
} | |
//0 Mary | |
//1 had | |
//2 a | |
//3 little | |
//4 lamb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment