Created
August 29, 2023 14:21
-
-
Save SpaghettDev/ffafe6522c4f7bf7cd70f5f254ecfa53 to your computer and use it in GitHub Desktop.
Python-like 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
/** | |
* Python-like range function | |
* | |
* @param start {Number} Start value, inclusive, if end isn't provided, start is end | |
* @param end {Number|null} End value, exclusive, defaults to null | |
* @param step {Number} Step value, default to 1 | |
* @returns {Array} [start, start+step, start+step*2, ..., end - 1] | |
*/ | |
const range = (start, end=null, step=1) => { | |
if (end == null) { | |
// start is actually end because 1 arg provided | |
return [...Array(start).keys()]; | |
} | |
if (end <= start && step > 0) { | |
return []; | |
} | |
if (step < 0) { | |
return range(end + 1, start + 1, -step).reverse(); | |
} | |
return [...Array(end).keys()].filter(i => i > start - 1).filter(i => i % step == 0); | |
}; | |
module.exports = range; | |
/* Usage: | |
for (let x of range(6)) { | |
console.log(x); // 0, 1, 2, 3, 4, 5 | |
} | |
for (let x of range(5, 7)) { | |
console.log(x); // 5, 6 | |
} | |
for (let x of range(0, 10, 2)) { | |
console.log(x); // 0, 2, 4, 6, 8 | |
} | |
for (let x of range(6, 1, -1)) { | |
console.log(x); // 6, 5, 4, 3, 2 | |
} | |
for (let x of range(6, 1, -2)) { | |
console.log(x); // 6, 4, 2 | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment