Skip to content

memoize minimumTokenRankContainingGrapheme #1825

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 6, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions packages/cursorless-engine/src/util/allocateHats/HatMetrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,14 @@ export function minimumTokenRankContainingGrapheme(
tokenRank: number,
graphemeTokenRanks: { [key: string]: number[] },
): HatMetric {
return ({ grapheme: { text } }) =>
min(graphemeTokenRanks[text].filter((r) => r > tokenRank)) ?? Infinity;
return memoizedHatMetric(
({ grapheme: { text } }): number => {
return (
min(graphemeTokenRanks[text].filter((r) => r > tokenRank)) ?? Infinity
);
},
({ grapheme }) => grapheme.text,
);
}

/**
Expand Down Expand Up @@ -85,3 +91,29 @@ export function penaltyEquivalenceClass(hatStability: HatStability): HatMetric {
return (_) => 0;
}
}

/**
* Memoizes a hat metric based on a key function.
* Hat allocation can be highly repetitive across any given dimension
* (grapheme, hat style, etc).
* This helps us avoid accidentally quadratic behavior in the number of tokens
* in minimumTokenRankContainingGrapheme.
* @param fn The hat metric to memoize
* @param key A function that returns a key for a given hat candidate
* @returns A memoized version of the hat metric
*/
function memoizedHatMetric(
fn: HatMetric,
key: (hat: HatCandidate) => any,
): HatMetric {
const cache = new Map<any, number>();
return (hat: HatCandidate): number => {
const k = key(hat);
if (cache.has(k)) {
return cache.get(k) as number;
}
const result = fn(hat);
cache.set(k, result);
return result;
};
}