一种缓存方法
function test (fn) {
var cache = {}
return function () {
// 等价于add函数
var args = JSON.stringify(arguments)
if (!cache[args]) {
cache[args] = fn(arguments)
}
return cache[args]
}
}
var add = test(function (args) {
var argLen = args.length,
item,
res = 0
for (var i = 0; i < argLen; i++) {
item = args[i]
res += item
}
return res
})
console.log(add(1, 2, 3)) // 6
左倾函数
function compose () {
var args = [].slice.call(arguments)
return function (x) {
return args.reduceRight(function (prev, cur) {
return cur(prev)
}, x)
}
}
function compose2 () {
let args = [].slice.call(arguments)
return x => args.reduceRight((res,cb) => cb(res), x)
}
var toUpperCase = x => x.toUpperCase()
var split = x => x.split('')
var reverse = x => x.reverse()
var join = x => x.join('')
var f = compose2(join, reverse, split, toUpperCase)
console.log(f('hello'))
网友评论