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

本文介绍了如何使用JavaScript实现自定义比较函数finder,并通过实例展示了如何在people数组中找到最大年龄、特定属性值以及满足特定条件的对象。通过plucker函数提取键值,结合内置库(_.identity, Math.max)和自定义逻辑,探讨了函数式编程在数据操作中的应用。
摘要由CSDN通过智能技术生成
// 实现一个比较函数
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)












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值