Last active
December 28, 2023 13:27
-
-
Save jonurry/7281f3e527a8c79495ebf1b8bec8edc2 to your computer and use it in GitHub Desktop.
4.1 Sum of a Range (Eloquent JavaScript Solutions)
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
// step parameter is optional | |
// if step is not passed in, | |
// and start is less than or equal to end, | |
// then step = 1, else step = -1 | |
function range(start, end, step = start <= end ? 1 : -1) { | |
let result = []; | |
// loop iterates up for positive step values | |
// and iterates down for negative step values | |
for (let i = start; step >= 0 ? i <= end : i >= end; i+=step) { | |
result.push(i); | |
} | |
return result; | |
} | |
function sum(numbers) { | |
result = 0; | |
for (let num of numbers) { | |
result += num; | |
} | |
return result; | |
} | |
console.log(range(1, 10)); | |
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
console.log(range(1, 10, 2)); | |
// → [1, 3, 5, 7, 9] | |
console.log(range(5, 2, -1)); | |
// → [5, 4, 3, 2] | |
console.log(range(5, 2)); | |
// → [5, 4, 3, 2] | |
console.log(range(10, 1, -3)); | |
// → [10, 7, 4, 1] | |
console.log(sum(range(1, 10))); | |
// → 55 | |
console.log(sum(range(1, 10, 2))); | |
// → 25 | |
console.log(sum(range(10, 1, -3))); | |
// → 22 (10 + 7 + 4 + 1) |
Thank you so so so much indeed really helpful
especially with explain.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
Building up an array is most easily done by first initializing a binding to [] (a fresh, empty array) and repeatedly calling its
push
method to add a value. Don’t forget to return the array at the end of the function.Since the end boundary is inclusive, you’ll need to use the <= operator rather than < to check for the end of your loop.
The
step
parameter can be an optional parameter that defaults (using the = operator) to 1.Having
range
understand negativestep
values is probably best done by writing two separate loops—one for counting up and one for counting down—because the comparison that checks whether the loop is finished needs to be >= rather than <= when counting downward.It might also be worthwhile to use a different default
step
, namely, -1, when the end of the range is smaller than the start. That way,range(5, 2)
returns something meaningful, rather than getting stuck in an infinite loop. It is possible to refer to previous parameters in the default value of a parameter.