Skip to content

Instantly share code, notes, and snippets.

@sergeimuller
Last active July 10, 2018 11:40
Show Gist options
  • Save sergeimuller/5c0cbdb5acad7b0923751aac6cc6f62d to your computer and use it in GitHub Desktop.
Save sergeimuller/5c0cbdb5acad7b0923751aac6cc6f62d to your computer and use it in GitHub Desktop.
ES6 implementation of python-like range function
/*
TODO: Fix case where startOrRange is
*/
function range(startOrRange, end = null, step = null) {
if (!startOrRange) return null; // Return null if no parameters are passed
const rangeArray = []; // Array to be populated
if (!end && !step) { // One parameter
for (let i = 0; // Set starting point to zero
Math.sign(startOrRange) === -1 ? i > startOrRange : i < startOrRange; // Update the test based on the sign of startOrRange
Math.sign(startOrRange) === -1 ? i-- : i++ // Update the sign of the iterator based on the sign of startOrRange
) {
rangeArray.push(i); // Add the current index to rangeArray
}
} else if (!step) { // Two parameters
for (let i = startOrRange; // Set the starting point to startOrRange
Math.sign(end) === -1 ? i > end : i < end; // Update the test based on the sign of end
Math.sign(end) === -1 ? i-- : i++ // Update the sign of the iterator based on the sign of end
) {
rangeArray.push(i); // Add the current index to rangeArray
}
} else { // Three parameters
for (let i = startOrRange; // Set the starting point to startOrRange
Math.sign(end) === -1 ? i > end : i < end; // Update the test based on the sign of end
Math.sign(step) === -1 ? i += step : i -= step // Update the sign of the iterator based on the sign of step
) {
rangeArray.push(i); // Add the current index to rangeArray
}
}
return rangeArray // Return the rangeArray
}
// Example usage
// One parameter
for (let oneParameter of range(5)) {
console.log({oneParameter})
}
// Two parameters
for (let twoParameters of range(3, 6)) {
console.log({twoParameters})
}
// Three parameters
for (let threeParameters of range(4, 10, 2)) {
console.log({threeParameters})
}
// Going backwards
for (let goingBackwards of range(0, -10, -2)) {
console.log({goingBackwards})
}
/*
Usage:
range(startOrRange)
startOrRange: Number of integers (whole numbers) to generate, starting from zero. eg. range(3) == [0, 1, 2]
range([startOrRange], end[, step])
startOrRange: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step: Difference between each number in the sequence.
Note:
All parameters must be integers.
All parameters can be positive or negative.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment