Remove falsy or rejected values in place without allocating
A live chart keeps a buffer of 200,000 sensor samples. Dropped readings arrive as null, NaN, or 0, and the buffer is cleaned many times a second. Allocating a new array on every clean causes garbage-collection pauses, and calling splice in a loop shifts the whole tail on every removal. Implement compactInPlace(array, keep), which removes unwanted values by moving the kept ones forward inside the same array.
compactInPlace(array, keep?) // => array (the same reference)
keep, keep every truthy value. The removed values are the falsy ones: false, 0, -0, 0n, '', null, undefined, and NaN.keep, call keep(value, index) and keep the value when it returns a truthy result. index is the value’s position in the array before compaction.keep exactly once per element, in index order.keep is never called for them.length is the number of kept values.splice, filter, or copyWithin.const samples = [21.5, null, 22.1, NaN, 0, 22.4, undefined];
compactInPlace(samples);
// => [21.5, 22.1, 22.4]
samples.length; // => 3 (the same array was compacted)
compactInPlace(['ok', '', 'warn', false, 'error']);
// => ['ok', 'warn', 'error']
compactInPlace([3, 0, -2, 7, 0], (value) => value !== null);
// => [3, 0, -2, 7, 0] (a custom rule can keep falsy values)
compactInPlace(['a', 'b', 'c', 'd', 'e'], (_, index) => index % 2 === 0);
// => ['a', 'c', 'e']
compactInPlace([1, , 2, , , 3]);
// => [1, 2, 3]