Skip to content
Snippets Groups Projects
Unverified Commit 0d6a8882 authored by Sergei Zharinov's avatar Sergei Zharinov Committed by GitHub
Browse files

feat: Add `filterMap` utility for fast array transforms (#23252)

parent 54dcdf01
Branches
Tags
No related merge requests found
import { filterMap } from './filter-map';
describe('util/filter-map', () => {
it('should return an empty array when given an empty array', () => {
const input: unknown[] = [];
const output = filterMap(input, () => 42);
expect(output).toBe(input);
expect(output).toBeEmpty();
});
it('should return an array with only the mapped values that pass the filter', () => {
const input = [0, 1, 2, 3, 4];
const output = filterMap(input, (n) => n * n);
expect(output).toBe(input);
expect(output).toEqual([1, 4, 9, 16]);
});
});
import is 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 (is.truthy(res)) {
array[newIdx] = res as never;
newIdx += 1;
}
}
const deletedCount = length - newIdx;
if (deletedCount) {
array.length = length - deletedCount;
}
return array as never;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment