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

Implement curry() #33

Open
cheatsheet1999 opened this issue Sep 11, 2021 · 0 comments
Open

Implement curry() #33

cheatsheet1999 opened this issue Sep 11, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

Currying is a useful technique used in JavaScript applications.

Please implement a curry() function, which accepts a function and return a curried one.

Here is an example

const join = (a, b, c) => {
   return `${a}_${b}_${c}`
}

const curriedJoin = curry(join)

curriedJoin(1, 2, 3) // '1_2_3'

curriedJoin(1)(2, 3) // '1_2_3'

curriedJoin(1, 2)(3) // '1_2_3'

Regular function

function curry(fn) {
    return function curried(...args) {
        // 1. if enough args, call func
        // 2. if not enough, bind the args and wait for new one

        if (args.length >= fn.length) {
            // 'this' is pointing to Window, apply is used to call the function fn
            //console.log(this)
            return fn.apply(this, args)
        } else {
            // 'this' is pointing to Window
            //console.log(this)
            return curried.bind(this, ...args)

        }
    }
}

Using arrow function, this is no need to apply or bind, since 'this' in arrow function inherited from the parent scope
Sep-10-2021 22-11-34

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
         return fn(...args);
       } else {
         return (...args2) => curried(...args, ...args2);
       }
    }
}
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

1 participant