函数柯里化
柯里化主要从某种意义上,应用的闭包的概念,将值存起来,其次满足柯里化的条件就是需要返回一个函数
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>函数柯里化</title>
</head>
<body>
<script type="text/javascript">
function add(...values) {
let sum = 0;
for(var val of values) {
sum += val;
}
return sum;
}
Function.prototype.curry = function() {
let slice = Array.prototype.slice;
let defaultValue = slice.call(arguments);
let that = this;
return function() {
// debugger;
return that.apply(this, defaultValue.concat(slice.call(arguments)))
}
}
let add1 = add.curry(1,2);
console.log(add1(5)); //8
console.log(add1(3)); //6
</script>
</body>
</html>
思考题,如何通过柯里化的概念实现add(1)(2)(3)()只要小括号有值进行累加,结果为6
const countMoney = (function() {
let money = 0
let args = []
const res = function() {
if(arguments.length === 0) {
for(let i = 0; i < args.length; i++) {
money += args[i]
}
return money
} else {
// arguments 是个类数组来着,应该用展开符展开才能push进去
args.push(...arguments)
return res
}
}
return res
})()
// 2018-01-01 存了1毛钱
countMoney(1)
// 2018-01-02 存了2毛钱
countMoney(2)
// 2018-01-03 存了3毛钱
countMoney(3)
// 2018-01-04 存了4毛钱
countMoney(4)
//一年以后
// 统计这笔巨额存款 输出结果为 10
console.log(countMoney())
// 你还可以装逼地进行花式统计,结果同样是10
countMoney(1)(2)(3)(4)()