Currying
# curry function
packages/fp/src/curry.ts:105curry<T extends (...args: any[]) => any>(fn: T): Curried<Args<T>, Return<T>>Creates a curried version of a function. A curried function can be called
with all arguments at once for immediate execution, or with arguments
one at a time (or in chunks) for partial application, returning new
functions until all arguments are received.
This utility favors “data-last” arguments for better composability, meaning
the data array should typically be the last parameter of the function
being curried.
Type parameters
- T
- The type of the function to curry.
Parameters
| Name | Type | Description |
|---|---|---|
| fn | T | The function to curry. |
Returns
Curried<Args<T>, Return<T>>A new function that is a curried version of
fn.Example
import { curry } from './curry';
// Example: A simple sum function with data-last
function sum(offset: number, numbers: number[]): number {
return numbers.reduce((acc, val) => acc + val + offset, 0);
}
const curriedSum = curry(sum);
// Partial application (curried form)
const sumWithOffsetOfTen = curriedSum(10);
console.log(sumWithOffsetOfTen([1, 2, 3])); // Output: 16
// Immediate execution (all arguments at once)
console.log(curriedSum(5, [1, 2, 3])); // Output: 11
// Example with a function returning a complex type (like LinearRegressionResult)
type Point = { x: number; y: number };
type RegressionResult = { ok: boolean, m?: number, b?: number, error?: string };
function _calculateRegression(options: { includeRSquared: boolean }, data: Point[]): RegressionResult {
// ... actual calculation logic ...
return { ok: true, m: 1, b: 0 };
}
const calculateRegression = curry(_calculateRegression);
// Partial application
const regressionWithRSquared = calculateRegression({ includeRSquared: true });
const resultPartial = regressionWithRSquared([{ x: 1, y: 1 }]);
console.log(resultPartial);
// Immediate execution
const resultImmediate = calculateRegression({ includeRSquared: false }, [{ x: 1, y: 1 }]);
console.log(resultImmediate);