0

I've been learning about currying functions and I understood the basic examples I read up on, however I'd really like to understand this example that was given of an advanced function but I'm finding it confusing, if anyone can help break it down that would be great, I understand curry takes in a function and then this function's arguments are gathered into an array with ...args but I'm not sure about the logic after or how it's working.

I'd also like to know what the value for (...args) is and where it is coming from? and what is happening with the line where the function is being bound to args again.

const curry = (fn) => {
  return curried = (...args) => {
    if (fn.length !== args.length) {
      return curried.bind(null, ...args)
    }
    return fn(...args);
  };
}
const totalNum = (x, y, z) => {
  return x + y + z
}
const curriedTotal = curry(totalNum);
console.log(curriedTotal(10)(20)(30));
j obe
  • 1,759
  • 4
  • 15
  • 23
  • 1
    The critical thing to understand is that the `.length` property of a function is the number of parameters it takes. So `fn.length !== args.length` is testing whether the function was called with enough arguments for all the parameters. – Barmar May 15 '23 at 19:03
  • 1
    This is a poor way to do it because it's using the global variable `curried`. This means you can only have one curried function at a time. – Barmar May 15 '23 at 19:05
  • …and really it should be `fn.length > args.length` not `!==` – Bergi May 15 '23 at 19:37
  • @Barmar so `fn.length` refers to the number of placeholder parameters in the function definition of `fn` so if `(a,b,c,d) => {}` was passed in, the length would be 4? – j obe May 15 '23 at 19:51
  • Yes, that's correct. `totalNum.length == 3` – Barmar May 15 '23 at 19:52
  • I'm not sure why `curried.bind` is being used next either, I can't work this function out – j obe May 15 '23 at 19:52
  • where does the value for `...args.length` come from then, is it going to be 1 because `curriedTotal(10)(20)(30)` only has one argument of 10? – j obe May 15 '23 at 19:55
  • @jobe Please [edit] your post to add the clarified questions – Bergi May 15 '23 at 19:57
  • You may want to take a look at https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind. Also step through your code with a debugger. – Bergi May 15 '23 at 19:59
  • @Bergi do you mean add the specific questions I asked in the comments or the details from Barmar? – j obe May 15 '23 at 20:16
  • @jobe I was referring to your previous two comments – Bergi May 15 '23 at 21:13

0 Answers0