-1

I want to implement an arrow function which is equivalent to another normal function works like the following example:

f(h)(a1)(a2)...(an) works like h(a1, a2, ..., an).

I think I have to implement it with the following psuedocode, but I don't know how can I find out what is the number of h function arguments?

pseudocode:

function h (...varArgs) {

}

var f = (h) => {
    return ...
}
Somehow
  • 41
  • 7
  • 2
    How would you indicate to a curried function that the last parameter has been supplied? Let me rephrase: You can't have a true variadic curried function, as those features are mutually exclusive due to the design. – Patrick Roberts Nov 01 '18 at 18:52
  • @PatrickRoberts would you please give me more clues? – Somehow Nov 01 '18 at 18:54
  • It's not a clue, it's a statement that what you're requesting is not possible exactly as you've specified. – Patrick Roberts Nov 01 '18 at 18:54
  • @PatrickRoberts I mean that the function 'h(a1, a2, ..., an)' works exactly like 'f(h)(a1)(a2)..(an)' using arrow function and closure – Somehow Nov 01 '18 at 18:56
  • A "rest parameter" means a variadic function. If what you're requesting is a transformation from a function with a fixed number of arguments, that's not the same thing. Don't say "rest parameter" if that's not what you mean. – Patrick Roberts Nov 01 '18 at 18:57
  • @PatrickRoberts both h and f function have variable arguments. – Somehow Nov 01 '18 at 19:00

1 Answers1

1

One-liner:

let curry = fn => (fn.length < 2) ? fn : x => curry(fn.bind(0, x))
//

let h = (a, b, c) => a + '/' + b + '/' + c
console.log(curry(h)(1)(2)(3))

Reads: "if the arity (number of arguments) is 0 or 1, curry f = f, otherwise create a function with one argument which invokes a curried version of the input function with the first parameter fixed in a closure.

Of course, this won't work if the arity (fn.length) is unknown. To handle true variadic functions, the only option is to add a to-value method (toString/valueOf) to the curried function, so that it might work in some contexts:

let curryVar = fn => x => {
  let b = fn.bind(0, x), f = curryVar(b)
  f.toString = b
  return f
}

let hv = (...xs) => xs.join('|')

console.log(curryVar(hv)(1)(2)(3) + "!")
georg
  • 211,518
  • 52
  • 313
  • 390
  • Would you please give me some explanation to find out what does it really do? – Somehow Nov 01 '18 at 19:02
  • It has variable arguments so the length and the number of arguments are unknown. – Somehow Nov 01 '18 at 19:04
  • @Somehow if you had read what I already told you in comments, currying a variadic function is impossible without specifying a way to indicate the last parameter to the curried function. What you're currently requesting is impossible. – Patrick Roberts Nov 01 '18 at 19:05
  • I've updated the question. Would you please guide me or add it in your post how to remove its bugs? – Somehow Nov 01 '18 at 23:33