Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active November 27, 2018 11:48
Show Gist options
  • Save harrisonmalone/9c1ad75ab400fe1a3d47ad2eebaf6541 to your computer and use it in GitHub Desktop.
Save harrisonmalone/9c1ad75ab400fe1a3d47ad2eebaf6541 to your computer and use it in GitHub Desktop.
nice challenge that would work in any language
// As a bonus assignment, modify your range function to take an optional third argument that indicates the “step” value used when building the array. If no step is given, the elements go up by increments of one, corresponding to the old behavior. The function call
// range(1, 10, 2)
// should return
// [1, 3, 5, 7, 9]
// Make sure it also works with negative step values so that
// range(5, 2, -1)
// produces
// [5, 4, 3, 2]
// https://eloquentjavascript.net/Eloquent_JavaScript.pdf
function range(start, end, step) {
if (step < 0) {
return stepDown(start, end, step)
}
else {
return stepUp(start, end, step)
}
}
function stepUp(start, end, step) {
arr = [start]
while (end > start) {
start = start + step
if (end < start) {
break;
}
arr.push(start)
}
return arr
}
function stepDown(start, end, step) {
arr = [start]
step = step * -1
while (end < start) {
start = start - step
if (end > start) {
break;
}
arr.push(start)
}
return arr
}
console.log(range(5, 2, -1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment