Last active
October 3, 2016 21:40
-
-
Save ijsnow/8c8467a8eac65ace3b7c8447f0f57251 to your computer and use it in GitHub Desktop.
range and sum from http://eloquentjavascript.net/04_data.html#h_TcUD2vzyMe
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
function range(start, end, order) { | |
var arr = [], i; | |
if (order === -1) { | |
for (i = start; i >= end; i--) { | |
arr.push(i); | |
} | |
} else { | |
for (i = start; i <= end; i++) { | |
arr.push(i); | |
} | |
} | |
return arr; | |
} | |
console.log(range(1, 10)); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] | |
console.log(range(5, 2, -1)); // [ 5, 4, 3, 2 ] | |
function sum(arr) { | |
var total = 0, i = 0; | |
for (; i < arr.length; i++) { | |
total += arr[i]; | |
} | |
return total; | |
} | |
console.log(sum(range(1, 10))); // 55 | |
console.log(sum(range(5, 2, -1))); // 14 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment