-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsum_of_a_range.js
More file actions
40 lines (33 loc) · 1.42 KB
/
sum_of_a_range.js
File metadata and controls
40 lines (33 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*The sum of a range
The introduction of this book alluded to the following as a nice way to compute the sum of a range of numbers:
console.log(sum(range(1, 10)));
Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.
Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55.
As a bonus assignment, modify your range function to take an optional third argument that indicates the “step” value used to build up the array. If no step is given, the array 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].
*/
function range(start, end, step) {
var array = [];
if (step == undefined) step = 1;
if (step < 0) {
for (var i = start; i >= end; i += step) {
array.push(i);
}
}
else {
for (var i = start; i <= end; i+=step) {
array.push(i);
}
}
return array;
}
function sum(arr) {
var total = 0;
for (var i = 0; i <= arr.length; i++) {
total = total + i;
}
return total;
}
console.log(sum(range(1, 10)));
// → 55
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]