Skip to content

Instantly share code, notes, and snippets.

@jonurry
Last active December 28, 2023 13:27
Show Gist options
  • Save jonurry/7281f3e527a8c79495ebf1b8bec8edc2 to your computer and use it in GitHub Desktop.
Save jonurry/7281f3e527a8c79495ebf1b8bec8edc2 to your computer and use it in GitHub Desktop.
4.1 Sum of a Range (Eloquent JavaScript Solutions)
// 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)
@web-dev-london
Copy link

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