js-读书笔记-函数式编程-高等函数-比较函数的实现

// 实现一个比较函数
const _ = require('../lib/underScore.js')
// 取出键值函数生成器
function plucker(fileId) {
  return function(obj) {
    return (obj && obj[fileId])
  }
}

let people = [
  {name: "js", age: 88},
  {name: 'go', age: 12},
]

let res = _.max(people, function(p){return p.age})
console.log(res)

// valueFn过滤分解参数,bestFn比较函数
function finder(valueFn, bestFn, coll) {
  return _.reduce(coll, function(best, current) {
    let bestValue = valueFn(best)
    let currentValue = valueFn(current)
    return (bestValue === bestFn(bestValue, currentValue)) ? best : current
  })
}
let m = finder(_.identity, Math.max, [1,2,3,4,5])
console.log(m)

let age = finder(plucker('age'), Math.max, people)
console.log(age)

let name = finder(plucker('name'), function(x, y) {return (x.charAt(0) === "g") ? x : y}, people)
console.log(name)

// 对finder函数,valueFn和bestFn进行合并,只需要传入fun。
function best(fun, coll) {
  return _.reduce(coll, function(x, y) {
    return fun(x,y) ? x: y
  })
}

let b = best(function(x,y) {return x > y}, [1,2,3,4,5])
console.log(b)

age = best(function(x, y) {
  let p = plucker('age');
  return p(x) > p(y)
}, people)
console.log(age)

name = best(function(x,y) {
  let p = plucker('name')
  return p(x).charAt(0) === 'g'
}, people)
console.log(name)












你可能感兴趣的:(js函数式编程,javascript)