mirror of
https://github.com/Microsoft/vscode
synced 2024-06-30 23:04:56 +00:00
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:
parent
f9238dd94a
commit
e6d29e4ba1
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
});
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user