0
点赞
收藏
分享

微信扫一扫

js 柯里化

you的日常 2022-06-30 阅读 31
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const curry = (fn) => {
return function curriedFn(...args) {
if (args.length < fn.length) {
return function () {
return curriedFn.apply(
null,
args.concat([].slice.call(arguments))
)
}
}
return fn.apply(null, args)
}
}
const add = (a, b) => {
return a + b
}

console.log(curry(add)(1)(2))

const add1 = (a, b, c, d, e) => {
return a + b + c + d + e
}
console.log(curry(add1)(1)(2)(3)(4)(5))

const add2 = function() {
let _args = Array.prototype.slice.call(arguments)
let _adder = function () {
_args.push(...arguments)
return _adder
}
_adder.toString = function () {
return _args.reduce(function (a, b) {
return a + b
})
}
return _adder
}

console.log(add2(1)(2))
console.log(add2(1, 2, 3)(4))
</script>
</body>
</html>

 


举报

相关推荐

0 条评论