Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

curry柯里化 #63

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

curry柯里化 #63

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

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))
@bearki99
Copy link

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;
}

@veneno-o
Copy link
Contributor

function curry(fn){
    return function temp(...args){
        if(args.length >= fn.length){
            return fn(...args);
        }else{
            return function(...newArgs){
                return temp(...args, ...newArgs)
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants