Skip to content

Commit 37ba8bc

Browse files
committed
Attempt to memoize just core function
1 parent a4e9a2e commit 37ba8bc

File tree

1 file changed

+8
-35
lines changed

1 file changed

+8
-35
lines changed

packages/cursorless-engine/src/util/allocateHats/HatMetrics.ts

Lines changed: 8 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { CompositeKeyMap, HatStability, TokenHat } from "@cursorless/common";
2-
import { min } from "lodash";
2+
import { memoize, min } from "lodash";
33
import { HatCandidate } from "./allocateHats";
44

55
/**
@@ -50,14 +50,13 @@ export function minimumTokenRankContainingGrapheme(
5050
tokenRank: number,
5151
graphemeTokenRanks: { [key: string]: number[] },
5252
): HatMetric {
53-
return memoizedHatMetric(
54-
({ grapheme: { text } }): number => {
55-
return (
56-
min(graphemeTokenRanks[text].filter((r) => r > tokenRank)) ?? Infinity
57-
);
58-
},
59-
({ grapheme }) => grapheme.text,
60-
);
53+
const coreMetric = memoize((graphemeText: string): number => {
54+
return (
55+
min(graphemeTokenRanks[graphemeText].filter((r) => r > tokenRank)) ??
56+
Infinity
57+
);
58+
});
59+
return ({ grapheme: { text } }) => coreMetric(text);
6160
}
6261

6362
/**
@@ -91,29 +90,3 @@ export function penaltyEquivalenceClass(hatStability: HatStability): HatMetric {
9190
return (_) => 0;
9291
}
9392
}
94-
95-
/**
96-
* Memoizes a hat metric based on a key function.
97-
* Hat allocation can be highly repetitive across any given dimension
98-
* (grapheme, hat style, etc).
99-
* This helps us avoid accidentally quadratic behavior in the number of tokens
100-
* in minimumTokenRankContainingGrapheme.
101-
* @param fn The hat metric to memoize
102-
* @param key A function that returns a key for a given hat candidate
103-
* @returns A memoized version of the hat metric
104-
*/
105-
function memoizedHatMetric(
106-
fn: HatMetric,
107-
key: (hat: HatCandidate) => any,
108-
): HatMetric {
109-
const cache = new Map<any, number>();
110-
return (hat: HatCandidate): number => {
111-
const k = key(hat);
112-
if (cache.has(k)) {
113-
return cache.get(k) as number;
114-
}
115-
const result = fn(hat);
116-
cache.set(k, result);
117-
return result;
118-
};
119-
}

0 commit comments

Comments
 (0)