Skip to content

Latest commit

 

History

History
44 lines (33 loc) · 962 Bytes

4.1.1 高阶函数-传递函数.md

File metadata and controls

44 lines (33 loc) · 962 Bytes

从一个不是数字数组的对象中找到最大值

var people = [{name : "Fred", age : 65}, {name : "Lucy", age : 36}]
_max(people, function(p) { return p.age })

_.max受限于大于运算符号。创建finder函数,其参数为:

  • 生成可比较的值
  • 比较两个值返回最佳
function finder(valueFun, bestFun, coll) {
  return _.reduce(coll, function(best, current) {
    var bestValue = valueFun(best);
    var currentValue = valueFun(current);
    
    return (bestValue === bestFun(bestValue, currentValue)) ? best : current;
  })
}

finder(_.identity, Math.max, [1, 2, 3, 4])

另外一个例子:

finder(_.plucker('name'), function(x, y) {
  return (x.charAt(0) === "L") ? x : y
}, people)

简化:

function best(fun, coll) {
  return _.reduce(coll, function(x, y) {
     return fun(x, y) ? x : y;
  });
}

best(function(x, y) { return x > y }, [1, 2, 4, 5])