Files
RahulGautamSingh 76f911041a refactor: use named exports (#39196)
* use named exports

* fix test

* add missing imnport

* fix prettier
2025-11-10 12:00:35 +00:00

27 lines
637 B
TypeScript

import { isTruthy } from '@sindresorhus/is';
type Falsy = false | '' | 0 | 0n | null | undefined;
/**
* Filter and map an array *in place* with single iteration.
*/
export function filterMap<T, U>(array: T[], fn: (item: T) => Falsy | U): U[] {
const length = array.length;
let newIdx = 0;
for (let oldIdx = 0; oldIdx < length; oldIdx += 1) {
const item = array[oldIdx];
const res = fn(item);
if (isTruthy(res)) {
array[newIdx] = res as never;
newIdx += 1;
}
}
const deletedCount = length - newIdx;
if (deletedCount) {
array.length = length - deletedCount;
}
return array as never;
}