Skip to content

Instantly share code, notes, and snippets.

@fronx
Forked from theophani/gist:1322203
Created October 28, 2011 14:02
Show Gist options
  • Save fronx/1322338 to your computer and use it in GitHub Desktop.
Save fronx/1322338 to your computer and use it in GitHub Desktop.
best is also the best of the best
var max = function (a, b) {
return (a > b ? a : b);
};
var min = function (a, b) {
return (a > b ? b : a);
};
var best = function (fun, array) {
if (!array.reduce) return array;
return array.reduce(function (a, b) {
return fun(best(fun, a), best(fun, b));
});
};
var equals = function (a, b) {
var equal = (a === b);
console.log(a, b, equal);
return equal;
};
equals('z', best(max, ['a','b','z','c']));
equals( 6, best(max, [6]));
equals( 6, best(max, 6));
equals( 4, best(max, [1,2,3,4,1]));
equals( 8, best(max, [[1,2,3,4,1],[1,2,3,8,1],[1,2,3,4,1],[1,2,3,4,1],[1,2,3,4,1]]));
equals( 12, best(max, [[1,2,3,4,1],[1,[1,12,3,4,1],3,8,1],[1,2,3,4,1],[1,2,3,4,1],[1,2,3,4,1]]));
equals( -2, best(max, [-5,-2,-3]));
equals( 20, best(max, [[20,2,3,4,1],[1,[1,12,3,4,1],3,8,1],[1,2,3,4,1],[1,2,3,4,1],[1,2,3,4,1]]));
equals('a', best(min, ['a','b','z','c']));
equals( 6, best(min, [6]));
equals( 6, best(min, 6));
equals( 1, best(min, [1,2,3,4,1]));
equals( 1, best(min, [[1,2,3,4,1],[1,2,3,8,1],[1,2,3,4,1],[1,2,3,4,1],[1,2,3,4,1]]));
equals( 0, best(min, [[1,2,3,4,1],[1,[1,12,3,0,4,1],3,8,1],[1,2,3,4,1],[1,2,3,4,1],[1,2,3,4,1]]));
equals( -5, best(min, [-5,-2,-3]));
equals( -1, best(min, [[20,2,3,4,-1],[1,[1,12,3,4,1],3,8,1],[1,2,3,4,-1],[1,2,3,4,1],[1,2,3,4,1]]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment