diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 70200aae41..69acb41dc6 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -17,6 +17,7 @@ // Ethan Resnick // Jack Leigh // Keagan McClelland +// Tomas Szabo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -1027,6 +1028,13 @@ declare namespace R { */ memoize(fn: (...a: any[]) => T): (...a: any[]) => T; + /** + * A customisable version of R.memoize. memoizeWith takes an additional function that will be applied to a given + * argument set and used to create the cache key under which the results of the function to be memoized will be stored. + * Care must be taken when implementing key generation to avoid clashes that may overwrite previous entries erroneously. + */ + memoizeWith any>(keyFn: (...v: any[]) => string, fn: T): T; + /** * Create a new object with the own properties of a * merged with the own properties of object b. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index dbb697e658..81eb438535 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -309,6 +309,36 @@ R.times(i, 5); const isLong = memoStringLength('short') > 10; // false })(); +(() => { + interface Vector { + x: number; + y: number; + } + + let numberOfCalls = 0; + + function vectorSum(a: Vector, b: Vector): Vector { + numberOfCalls += 1; + return { + x: a.x + b.x, + y: a.y + b.y + }; + } + + const memoVectorSum = R.memoizeWith(JSON.stringify, vectorSum); + + memoVectorSum({ x: 1, y: 1 }, { x: 2, y: 2 }); // => { x: 3, y: 3 } + numberOfCalls; // => 1 + memoVectorSum({ x: 1, y: 1 }, { x: 2, y: 2 }); // => { x: 3, y: 3 } + numberOfCalls; // => 1 + memoVectorSum({ x: 1, y: 2 }, { x: 2, y: 3 }); // => { x: 3, y: 5 } + numberOfCalls; // => 2 + + // Note that argument order matters + memoVectorSum({ x: 2, y: 3 }, { x: 1, y: 2 }); // => { x: 3, y: 5 } + numberOfCalls; // => 3 +})(); + (() => { const addOneOnce = R.once((x: number) => x + 1); addOneOnce(10); // => 11