Skip to content

Latest commit

 

History

History
53 lines (42 loc) · 2.26 KB

File metadata and controls

53 lines (42 loc) · 2.26 KB

Solution

Submission link - https://bigfrontend.dev/problem/implement-curry/discuss/765

/**
 * @param { Function } func
 */
function curry(func) {

  // we need to return a function to make it curry-able. 
  return function curried(...args) {

    // if the passed arguments are greater than original function 'func' parameters
    // then we directly call `func` with passed arguments
    if(args.length >= func.length) {
      return func.apply(this, args);

    } else {
      // else we gather 2nd argument and pass it to `curried` function.
      // this will continue till arguments >= parameters
      return function next(...args2) {
        return curried.apply(this, args.concat(args2));
      }
    }
  }
}

Short story

I tried to attempt it but couldn't get actual logic. Such problems look simple but you learn a lot when you pay attention to details.
Example - I realized that apply and bind methods are powerful. I had to understand that why did few people use bind over apply.

In the apply method, you need to pass arguments all at once. In the bind, you can reserve them and when next time that function gets called, it will apply those arguments too.

Algorithm

  1. We create a function called curried that we return to take arguments
  2. We check if given arguments args >= function func parameters or not
  3. If the above condition is true then we call func with all arguments we received
  4. Else we return a new function which takes the next argument and call the curried function recursively

Code overview

  1. To make a function curry-able, we return a function curried
  2. The curried will take arguments args
  3. We will check if args.length (passed arguments) >= func.length (total parameters)
    1. If the above condition is true then we directly call func with passed arguments
    2. Else we will return another function (because few arguments are still pending) to collect the next arguments
  4. We will take those next arguments and recursively call curried function until main condition args.length (passed arguments) >= func.length is true

I'm excited to improve the solution and code walkthrough. Feel free to drop a comment, or send a PR or send memes @knowkalpesh.