-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththe-sum-of-a-range.js
36 lines (25 loc) · 1.15 KB
/
the-sum-of-a-range.js
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
// 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 example 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 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].
function range(start, end, step = 1) {
let number = []
if(end > start) {
for(let i = start; i <= end; i+= step) {
number.push(i)
}
} else if(end < start) {
for(let i = start; i >= end; i+= step) {
number.push(i)
}
}
return number
}
function sum(arr) {
return arr.reduce((a,b) => a + b)
}
console.log(range(1, 10))
console.log(range(5, 10, 2))
console.log(range(5, 2, -1))
console.log(sum(range(1,10)))