Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

curry柯里化

Sunny-117 opened this issue · comments

function add(a, b, c) {
    return a + b + c
}

function curry(fn) {
    let judge = (...args) => {
        if (args.length == fn.length) return fn(...args)
        return (...arg) => judge(...args, ...arg)
    }
    return judge
}
let addCurry = curry(add)
const res1 = addCurry(1, 2)(3)
const res2 = addCurry(1)(2)(3)
console.log(res1);
console.log(res2);

// //  通用实现1
// function currying(fn, length) {
//     length = length || fn.length;
//     return function (...args) {
//         return args.length >= length
//             ? fn.apply(this, args)
//             : currying(fn.bind(this, ...args), length - args.length)
//     }
// }
// //  通用实现2
// function currying(fn, length) {
//     return function (...args) {
//         if (args.length >= length) {
//             return args.slice(0, length).reduce((t, i) => t += i);
//         }
//         return function (..._args) {
//             return add.apply(null, [...args, ..._args]);
//         }
//     }
// }
// function add(...args) {
//     return args.reduce((t, i) => t + i)
// }
// var newAdd = currying(add, 3)
// console.log(newAdd(1, 2, 3))
// console.log(newAdd(1, 2)(3))
commented
function myCurrying(fn) {
  function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);
    } else {
      return function (...args2) {
        return curried.apply(this, args.concat(args2));
      };
    }
  }
  return curried;
}
function curry(fn){
    return function temp(...args){
        if(args.length >= fn.length){
            return fn(...args);
        }else{
            return function(...newArgs){
                return temp(...args, ...newArgs)
            }
        }
    }
}