CyrefJS
CCyrefJS
فا
Back to documentation
Function/Since 1.38.0

curry

Transforms a function into a curried function that can receive its arguments across multiple calls.

curry(fn):(...args: Partial<TArgs>) => unknown

Parameters

fn(...args: TArgs) => TResultrequired

The function to curry. Its declared parameter count is used to determine when all required arguments have been collected.

Returns

(...args: Partial<TArgs>) => unknown

A curried function that collects arguments across multiple calls and invokes the original function once enough arguments have been provided.

Examples

01

Basic usage

Provide the arguments across multiple function calls.

TypeScript
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);
// 15
02

Multiple arguments at once

Arguments can also be provided together in a single call.

TypeScript
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);
// 20
03

Three arguments

A function with three parameters can collect its arguments over multiple calls.

TypeScript
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);
// 6
04

Mixed argument groups

Arguments can be supplied in different group sizes across calls.

TypeScript
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);
// 14
05

Reusable partially applied function

The returned function can be stored and completed later with the remaining arguments.

TypeScript
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);
// 50
06

Collecting arguments

The function keeps collecting arguments until their total count reaches the original function's length.

TypeScript
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"
Built with@cyref/js·Official documentation