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