Skip to content

Commit

Permalink
Added cache to CharCaseFolding implementations (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
RunDevelopment committed Sep 13, 2023
1 parent f5f918c commit 3f68ed2
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/js/char-case-folding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,36 +27,36 @@ export interface CharCaseFolding {
}

const CHAR_CASE_FOLDING_UTF16: CharCaseFolding = {
toCharSet(char) {
toCharSet: boundedCache(char => {
return CharSet.fromCharacter(Maximum.UTF16, char);
},
}),
};
const CHAR_CASE_FOLDING_UTF16_I: CharCaseFolding = {
canonicalize: char => UTF16CaseFolding[char]?.[0] ?? char,
toCharSet(char) {
toCharSet: boundedCache(char => {
const folding = UTF16CaseFolding[char];
if (folding === undefined) {
return CharSet.fromCharacter(Maximum.UTF16, char);
} else {
return CharSet.fromCharacters(Maximum.UTF16, folding);
}
},
}),
};
const CHAR_CASE_FOLDING_UNICODE: CharCaseFolding = {
toCharSet(char) {
toCharSet: boundedCache(char => {
return CharSet.fromCharacter(Maximum.UNICODE, char);
},
}),
};
const CHAR_CASE_FOLDING_UNICODE_I: CharCaseFolding = {
canonicalize: char => UnicodeCaseFolding[char]?.[0] ?? char,
toCharSet(char) {
toCharSet: boundedCache(char => {
const folding = UnicodeCaseFolding[char];
if (folding === undefined) {
return CharSet.fromCharacter(Maximum.UNICODE, char);
} else {
return CharSet.fromCharacters(Maximum.UNICODE, folding);
}
},
}),
};

export function getCharCaseFolding(unicode: boolean, ignoreCase: boolean): CharCaseFolding;
Expand All @@ -76,3 +76,18 @@ export function getCharCaseFolding(flagsOrUnicode: Readonly<Flags> | boolean, ig
return ignoreCase ? CHAR_CASE_FOLDING_UTF16_I : CHAR_CASE_FOLDING_UTF16;
}
}

function boundedCache<A, B>(compute: (value: A) => B, maxSize: number = 100): (value: A) => B {
const cache = new Map<A, B>();
return value => {
let cached = cache.get(value);
if (cached === undefined) {
cached = compute(value);
if (cache.size >= maxSize) {
cache.clear();
}
cache.set(value, cached);
}
return cached;
};
}

0 comments on commit 3f68ed2

Please sign in to comment.