Start learning free

LESSON 145 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Curry in JavaScript

Practice

To curry a function means to let it take its arguments a few at a time. A curried add(a, b) can be called as add(1, 2) or as add(1)(2). Each call that has too few arguments gives back a new function that waits for the rest.

How many is enough? Every function has a length: the number of parameters it declares. ((a, b) => a + b).length is 2. Once a curried function has collected at least that many arguments, it calls the real function with all of them. A part-filled function keeps its arguments, so you can use it again and again:

const greet = curry((greeting, name) => greeting + ", " + name);
const hi = greet("Hi");   // a function: 1 of 2 arguments so far
hi("Ana");                // "Hi, Ana"
hi("Ben");                // "Hi, Ben"

The check curries a few functions, calls them in different ways and prints what comes back. Your code must print:

total = curry((price, quantity, discount) => price * quantity - discount); fn.length is 3:
  total(12, 2, 4) returns 20
  total(12)(2)(4) returns 20
  total(12, 2)(4) returns 20
  total(12)(2, 4) returns 20
  total(12) returns a function
  total(12)(2) returns a function
  calls of the real function: 4
Extra arguments go to the function too:
  countArgs(1)(2, 3) returns 3
A part-filled function can be used again and again:
  label("Mug") returns a function
  mug(12) returns "Mug $12"
  mug(10) returns "Mug $10"
  label("Lamp")(29) returns "Lamp $29"
One argument, and none:
  double(5) returns 10
  hello() returns "Hello"

Your task: write curry(fn). It returns a function named curried that takes any number of arguments. If it has at least fn.length of them, it returns fn called with them. Otherwise it returns a function that waits for more arguments and calls curried again with the old ones and the new ones.


Assignment
Follow the Coding Tutorial to write curry: the function curried, the call to fn once there are enough arguments, and the function that waits for more.


Hint
...args collects the arguments into an array, and fn(...args) spreads them back out. The waiting function must not forget the arguments it already has: pass the old ones first, then the new ones.


STEP 1 OF 3
    Ctrl + Enter to check

    Fe Curry in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free