Created
January 30, 2013 19:09
-
-
Save danielmoore/4675834 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
var array = [-3 , -6, -2, -56, -32, -5, -89, -32]; | |
function max1(array) { | |
var largest = array[0]; // start with the first item | |
for (i = 1; i < array.length; i++) // changed i to start at 1, to avoid extra work | |
if (array[i] > largest) { | |
largest = array[i]; | |
} | |
return largest; | |
} | |
// For thought... | |
function max2(arr) { | |
// Arrays have a nifty method called "reduce" that take a | |
// "accumulator" function and (optionally) an initial value. | |
// The accumulator takes two inputs and returns an accumulated | |
// value. The accumulator is called for each value in the array | |
// being given the previous accumulated value and the next item | |
// in the array. The first call to the accumulator is given the | |
// initial value, or, if it is not supplied, the first item in | |
// the array | |
return arr.reduce(function(a, b) { | |
// here I use the "terenary" operator ? : | |
// The terenary operator is like an inline if statement: | |
// return cond ? a : b; | |
// translates to: | |
// if (cond) { return a; } else { return b; } | |
return a > b ? a : b; | |
}); | |
} | |
// i.e., | |
function max2(arr) { return arr.reduce(function(a, b) { return a > b ? a : b; }); } | |
// Funnily enough, Javascript already has a max function which | |
// takes a list of values. i.e., Math.max(1, 2, 3) === 3 | |
// One of the interesting things about Javascript is | |
// that we can invoke a function using an array as the | |
// parameters. We do this with the apply method on functions. | |
function max3(arr) { return Math.max.apply(null, arr); } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment