Created
April 12, 2020 01:14
-
-
Save yitonghe00/534be677ae674c197fa0cd7aa683e617 to your computer and use it in GitHub Desktop.
Excises of Eloquent JavaScript 4th edition. Chapter 04 Problem 01. https://eloquentjavascript.net/04_data.html#i_8ZspxiCEC/
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
// Your code here. | |
const range = (start, end, step = 1) => { | |
const ans = []; | |
if (step > 0 && start < end) { | |
for (let i = start; i <= end; i += step) { | |
ans.push(i); | |
} | |
} else { | |
if (step > 0) step = -1; | |
for (let i = start; i >= end; i += step) { | |
ans.push(i); | |
} | |
} | |
return ans; | |
} | |
const sum = (arr) => { | |
let ans = 0; | |
for (let index in arr) { | |
ans += arr[index]; | |
} | |
return ans; | |
} | |
console.log(range(1, 10)); | |
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
console.log(range(5, 2)); | |
// → [5, 4, 3, 2] | |
console.log(sum(range(1, 10))); | |
// → 55 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment