|
1 | 1 | import { CompositeKeyMap, HatStability, TokenHat } from "@cursorless/common";
|
2 |
| -import { min } from "lodash"; |
| 2 | +import { memoize, min } from "lodash"; |
3 | 3 | import { HatCandidate } from "./allocateHats";
|
4 | 4 |
|
5 | 5 | /**
|
@@ -50,14 +50,13 @@ export function minimumTokenRankContainingGrapheme(
|
50 | 50 | tokenRank: number,
|
51 | 51 | graphemeTokenRanks: { [key: string]: number[] },
|
52 | 52 | ): 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); |
61 | 60 | }
|
62 | 61 |
|
63 | 62 | /**
|
@@ -91,29 +90,3 @@ export function penaltyEquivalenceClass(hatStability: HatStability): HatMetric {
|
91 | 90 | return (_) => 0;
|
92 | 91 | }
|
93 | 92 | }
|
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