Curry function

JavaScript, Function, Recursion · Oct 22, 2020

Curries a function.

  • Use recursion.
  • If the number of provided arguments (args) is sufficient, call the passed function fn.
  • Otherwise, use Function.prototype.bind() to return a curried function fn that expects the rest of the arguments.
  • If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. Math.min()), you can optionally pass the number of arguments to the second parameter arity.
const curry = (fn, arity = fn.length, ...args) =>
  arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
curry(Math.pow)(2)(10); // 1024
curry(Math.min, 3)(10)(50)(2); // 2

More like this

  • Uncurry function

    Uncurries a function up to depth n.

    JavaScript, Function · Oct 22, 2020

  • Pipe async functions

    Performs left-to-right function composition for asynchronous functions.

    JavaScript, Function · Oct 22, 2020

  • Converge branching functions

    Converges a list of branching functions into a single function and returns the result.

    JavaScript, Function · Jan 7, 2021