BFE 1. Implement curry()




What is currying?


Currying is a functional programming technique that allows me to partcially apply a function by breaking down the parameters into a series of functions that each function takes some of the parameters.



Example


add(1, 2, 3) -> add(1)(2)(3)

add(1, 2, 3) -> add(1, 2)(3)

add(1, 2, 3) -> add(1)(2, 3)



Thoughts:


Need to return a function for chaining the calls until all the arguments are provided.



Tips:




Code:


function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);
    } else {
      return function (...nextArgs) {
        return curried.apply(this, args.concat(nextArgs));
      };
    }
  };
}


Reference


Original link
Parameter vs Argument

Copyright © 2024 | All rights reserved.