Last active
November 27, 2018 11:48
-
-
Save harrisonmalone/9c1ad75ab400fe1a3d47ad2eebaf6541 to your computer and use it in GitHub Desktop.
nice challenge that would work in any language
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
// 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