Created
December 13, 2012 00:28
-
-
Save bgreenlee/4273000 to your computer and use it in GitHub Desktop.
A collection of useful Javascript functions #javascript
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
// sum an array, optionally providing a function to call on each element of the | |
// array to retrieve the value to sum | |
Array.prototype.sum = function(fn) { | |
return this.reduce(function(accum, elem) { | |
return accum + (fn ? fn(elem) : elem); | |
}, 0); | |
}; | |
// flatten an array | |
// [1,2,[3,4]] -> [1,2,3,4] | |
Array.prototype.flatten = function() { | |
return this.reduce(function(accum, elem) { return accum.concat(elem); }, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment