Created
March 31, 2016 03:16
-
-
Save NickBeeuwsaert/5422be43873b00be1134ab12723ca4db to your computer and use it in GitHub Desktop.
JS range function like in python
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
function range(start, stop, step=1) { | |
let length = 0; | |
if(arguments.length == 1) { | |
[start, stop, step] = [0, start, 1]; | |
} | |
[start, stop, step] = [start, stop, step].map(Math.floor); | |
if(step === 0) | |
throw new TypeError("step cannot be zero"); | |
if(step > 0 && start < stop) { | |
length = Math.floor(1 + (stop - 1 - start) / step); | |
} else if(step < 0 && start > stop) { | |
length = Math.floor(1 + (start - 1 - stop) / -step); | |
} | |
let ret = { | |
contains(val) { | |
return start < val && val < stop; | |
}, | |
[Symbol.iterator]() { | |
let idx = 0; | |
return { | |
next() { | |
let value = start + idx++ * step; | |
let done = idx > length; | |
return {value, done}; | |
} | |
}; | |
} | |
}; | |
Object.defineProperty(ret, "length", { | |
"writable": false, | |
"value": length | |
}); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment