Skip to content

Commit 9457eb4

Browse files
committed
add array#removeFastWithoutKeepingOrder
1 parent 3038b56 commit 9457eb4

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/vs/base/common/arrays.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,18 @@ export function equals<T>(one: ReadonlyArray<T> | undefined, other: ReadonlyArra
4646
return true;
4747
}
4848

49+
/**
50+
* Remove the element at `index` by replacing it with the last element. This is faster than `splice`
51+
* but changes the order of the array
52+
*/
53+
export function removeFastWithoutKeepingOrder<T>(array: T[], index: number) {
54+
const last = array.length - 1;
55+
if (index < last) {
56+
array[index] = array[last];
57+
}
58+
array.pop();
59+
}
60+
4961
/**
5062
* Performs a binary search algorithm over a sorted array.
5163
*

src/vs/base/test/common/arrays.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,19 @@ import * as assert from 'assert';
66
import * as arrays from 'vs/base/common/arrays';
77

88
suite('Arrays', () => {
9+
10+
test('removeFastWithoutKeepingOrder', () => {
11+
const array = [1, 4, 5, 7, 55, 59, 60, 61, 64, 69];
12+
arrays.removeFastWithoutKeepingOrder(array, 1);
13+
assert.deepStrictEqual(array, [1, 69, 5, 7, 55, 59, 60, 61, 64]);
14+
15+
arrays.removeFastWithoutKeepingOrder(array, 0);
16+
assert.deepStrictEqual(array, [64, 69, 5, 7, 55, 59, 60, 61]);
17+
18+
arrays.removeFastWithoutKeepingOrder(array, 7);
19+
assert.deepStrictEqual(array, [64, 69, 5, 7, 55, 59, 60]);
20+
});
21+
922
test('findFirst', () => {
1023
const array = [1, 4, 5, 7, 55, 59, 60, 61, 64, 69];
1124

0 commit comments

Comments
 (0)