Created
September 1, 2014 17:45
-
-
Save sawant/ad412381f273f67d4b5a to your computer and use it in GitHub Desktop.
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
/* | |
http://eloquentjavascript.net/04_data.html | |
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 range = []; | |
if( step === undefined ) step = 1; | |
if( step > 0 ) { | |
for( var i = start; i <= end; i += step ) | |
range.push( i ); | |
} else { | |
for( var i = start; i >= end; i += step ) | |
range.push( i ); | |
} | |
return range; | |
} | |
function sum( numbers ) { | |
var result = 0; | |
for( i = 0; i < numbers.length; i++ ) | |
result += numbers[i]; | |
return result; | |
} | |
console.log(sum(range(1, 10))); | |
// → 55 | |
console.log(range(5, 2, -1)); | |
// → [5, 4, 3, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment