Created
October 26, 2010 04:37
-
-
Save taiju/646315 to your computer and use it in GitHub Desktop.
reduceの使い方。汎用的な関数を作る時に超便利。
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
var sum = function(a) { | |
return a.reduce(function(x, y) { return x + y; }); | |
}; | |
var max = function(a) { | |
return a.reduce(function(x, y) { | |
if (x > y) return x; | |
return y; | |
}); | |
}; | |
var min = function(a) { | |
return a.reduce(function(x, y) { | |
if (x > y) return y; | |
return x; | |
}); | |
}; | |
var average = function(a) { | |
return a.reduce(function(x, y) { | |
if (y === a[a.length-1]) return (x + y) / a.length; | |
return x + y; | |
}); | |
}; | |
var filter = function(a) { | |
a.unshift([]); | |
return a.reduce(function(x, y) { | |
if (y) { | |
x.push(y); | |
return x; | |
} | |
return x; | |
}); | |
}; | |
var exist = function(a, val) { | |
return a.reduce(function(x, y) { | |
return (x === true || x === val || y === val) ? true : false; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment