strings: make 'count' much faster (#211732)

I noticed in doing a fix in copilot that our 'count' function was glacially slow. This is significantly faster.
This commit is contained in:
Connor Peet 2024-04-30 13:28:44 -07:00 committed by GitHub
parent f9238dd94a
commit e6d29e4ba1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 16 additions and 7 deletions

View File

@ -90,15 +90,14 @@ export function escapeRegExpCharacters(value: string): string {
}
/**
* Counts how often `character` occurs inside `value`.
* Counts how often `substr` occurs inside `value`.
*/
export function count(value: string, character: string): number {
export function count(value: string, substr: string): number {
let result = 0;
const ch = character.charCodeAt(0);
for (let i = value.length - 1; i >= 0; i--) {
if (value.charCodeAt(i) === ch) {
result++;
}
let index = value.indexOf(substr);
while (index !== -1) {
result++;
index = value.indexOf(substr, index + substr.length);
}
return result;
}

View File

@ -543,6 +543,16 @@ suite('Strings', () => {
assert.strictEqual(strings.removeAnsiEscapeCodesFromPrompt('\n\\[\u001b[01;34m\\]\\w\\[\u001b[00m\\]\n\\[\u001b[1;32m\\]> \\[\u001b[0m\\]'), '\n\\w\n> ');
});
test('count', () => {
assert.strictEqual(strings.count('hello world', 'o'), 2);
assert.strictEqual(strings.count('hello world', 'l'), 3);
assert.strictEqual(strings.count('hello world', 'z'), 0);
assert.strictEqual(strings.count('hello world', 'hello'), 1);
assert.strictEqual(strings.count('hello world', 'world'), 1);
assert.strictEqual(strings.count('hello world', 'hello world'), 1);
assert.strictEqual(strings.count('hello world', 'foo'), 0);
});
ensureNoDisposablesAreLeakedInTestSuite();
});