【Underscore.js】_.maxを読んだ
jashkenas/underscoreの_.maxを読んだ。
概要
_.max(list, [iteratee], [context])
listの中の最大値を返す。 iterateeに関数が与えられると、その返り値が比較基準になる。 リストが空だと-Infinityが返るので、isEmptyを使って判定すること。
var list = [ {age: 20, sex: "male", country: "JP", name: "hoge"}, {age: 22, sex: "male", country: "US", name: "fuga"}, {age: 20, sex: "female", country: "US", name: "piyo"}, {age: 45, sex: "male", country: "JP", name: "HUGA"}, {age: 20, sex: "male", country: "JP", name: "hoge"} ]; var x = _.max(list, function(elem){return elem.age;}); console.log(x); // {age: 45, sex: "male", country: "JP", name: "HUGA"}
ソースコード
_.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; };
中で何をやっているかわかりやすい。使う機会が多そう。