1.38.0curry
Transforms a function into a curried function that can receive its arguments across multiple calls.
curry(fn):(...args: Partial<TArgs>) => unknownParameters
fn(...args: TArgs) => TResultrequiredThe function to curry. Its declared parameter count is used to determine when all required arguments have been collected.
Returns
(...args: Partial<TArgs>) => unknownA curried function that collects arguments across multiple calls and invokes the original function once enough arguments have been provided.
Examples
Basic usage
Provide the arguments across multiple function calls.
import { curry } from "@cyref/js";
const add = (a: number, b: number) => a + b;
const curriedAdd = curry(add);
const result = curriedAdd(5)(10);
console.log(result);
// 15Multiple arguments at once
Arguments can also be provided together in a single call.
import { curry } from "@cyref/js";
const multiply = (a: number, b: number) => a * b;
const curriedMultiply = curry(multiply);
const result = curriedMultiply(4, 5);
console.log(result);
// 20Three arguments
A function with three parameters can collect its arguments over multiple calls.
import { curry } from "@cyref/js";
const sum = (a: number, b: number, c: number) => a + b + c;
const curriedSum = curry(sum);
const result = curriedSum(1)(2)(3);
console.log(result);
// 6Mixed argument groups
Arguments can be supplied in different group sizes across calls.
import { curry } from "@cyref/js";
const calculate = (
a: number,
b: number,
c: number,
) => a + b * c;
const curriedCalculate = curry(calculate);
const result = curriedCalculate(2, 3)(4);
console.log(result);
// 14Reusable partially applied function
The returned function can be stored and completed later with the remaining arguments.
import { curry } from "@cyref/js";
const multiply = (a: number, b: number) => a * b;
const curriedMultiply = curry(multiply);
const multiplyByTen = curriedMultiply(10);
const result = multiplyByTen(5);
console.log(result);
// 50Collecting arguments
The function keeps collecting arguments until their total count reaches the original function's length.
import { curry } from "@cyref/js";
const formatName = (
firstName: string,
lastName: string,
title: string,
) => `${title} ${firstName} ${lastName}`;
const curriedFormatName = curry(formatName);
const withName = curriedFormatName("John", "Doe");
const result = withName("Dr.");
console.log(result);
// "Dr. John Doe"