import _ from 'underScore'
import Utils from '../lib/utils.js'
// 递归和组合函数
// conjoin Disjoin 的实现
// checker的递归实现:andify
// 英文中ify是使...化。这里的意思是使函数and化
function andify(...preds) {
return function (...args) {
const everything = function(ps, truth) {
if(_.isEmpty(ps)) {
return truth
} else {
const [head, ...tail] = ps
return args.every(head) && everything(tail, truth)
}
}
return everything(preds, true)
}
}
function isEven(v) {
return v % 2 === 0
}
let evenNums = andify(_.isNumber, isEven) // 传入谓词函数
console.log(evenNums(1,2)) // false
console.log(evenNums(2,4,6,8)) // true
console.log(evenNums(2,4,6,8,9)) // false
function orify(...preds) {
return function(...args) {
const something = function(ps, truth) {
if(_.isEmpty(ps)) {
return truth
} else {
const [head, ...tail] = ps
return args.some(head) || something(tail, truth)
}
}
return something(preds, false)
}
}
const zero = x => x === 0
const isOdd = Utils.complement(isEven)
let zeroOrOdd = orify(isOdd, zero)
console.log(zeroOrOdd()) // false
console.log(zeroOrOdd(0,2,4,6)) // true
console.log(zeroOrOdd(2,4,6)) // false
js-读书笔记-函数式编程-递归-checker-andify&orify
最新推荐文章于 2024-11-03 16:40:52 发布