Here the fastest working implementation while keeping the same array ("mutable"):
function clearArray(array) {
while (array.length) {
array.pop();
}
}
FYI it cannot be simplified to while (array.pop())
: the tests will fail.
FYI Map and Set define clear()
, it would have seem logical to have clear()
for Array too.
TypeScript version:
function clearArray<T>(array: T[]) {
while (array.length) {
array.pop();
}
}
The corresponding tests:
describe('clearArray()', () => {
test('clear regular array', () => {
const array = [1, 2, 3, 4, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
test('clear array that contains undefined and null', () => {
const array = [1, undefined, 3, null, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
});
Here the updated jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152