[Ramda] Added memoizeWith definition (#24895)

* Ramda: added memoizeWith definition

* Ramda: added memoizeWith definition

* Ramda: added memoizeWith definition - narrowed generic
This commit is contained in:
Tomáš Szabo
2018-04-20 19:46:39 +02:00
committed by Ryan Cavanaugh
parent 2e1b78adc0
commit 68d4475fa9
2 changed files with 38 additions and 0 deletions

View File

@@ -17,6 +17,7 @@
// Ethan Resnick <https://github.com/ethanresnick>
// Jack Leigh <https://github.com/leighman>
// Keagan McClelland <https://github.com/CaptJakk>
// Tomas Szabo <https://github.com/deftomat>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
@@ -1027,6 +1028,13 @@ declare namespace R {
*/
memoize<T = any>(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<T extends (...args: any[]) => 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.

View File

@@ -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