Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created February 26, 2012 05:23
Show Gist options
  • Save ishiduca/1913409 to your computer and use it in GitHub Desktop.
Save ishiduca/1913409 to your computer and use it in GitHub Desktop.
Math.(min|max) で配列のmax, minメソッドの実装
var ap = Array.prototype;
if (! ap.forEach_) {
ap.forEach_ = function (f) {
for (var i = 0, len = this.length; i < len; i++) {
f(this[i], i);
}
};
}
if (! ap.grep) {
ap.grep = function (f) {
var that = [];
this.forEach_(function (a) {
if (f(a)) that.push(a);
});
return that;
};
}
if (! ap.max) {
ap.max = function () {
return Math.max.apply(null, this.grep(function (n) {
return (n === n - 0) ? true : false;
}));
};
}
if (! ap.min) {
ap.min = function () {
return Math.min.apply(null, this.grep(function (n) {
return (n === n - 0) ? true : false;
}));
};
}
var a = [ 'abc', 0, -23, 4, 3, -2, 9, '12' ];
console.log(a.max()); // 9
console.log(a.min()); // -23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment