deno.land / std@0.224.0 / collections / map_not_nullish.ts

map_not_nullish.ts
View Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.// This module is browser compatible.
/** * Returns a new array, containing all elements in the given array transformed * using the given transformer, except the ones that were transformed to `null` * or `undefined`. * * @example * ```ts * import { mapNotNullish } from "https://deno.land/std@$STD_VERSION/collections/map_not_nullish.ts"; * import { assertEquals } from "https://deno.land/std@$STD_VERSION/assert/assert_equals.ts"; * * const people = [ * { middleName: null }, * { middleName: "William" }, * { middleName: undefined }, * { middleName: "Martha" }, * ]; * const foundMiddleNames = mapNotNullish(people, (it) => it.middleName); * * assertEquals(foundMiddleNames, ["William", "Martha"]); * ``` */export function mapNotNullish<T, O>( array: Iterable<T>, transformer: (el: T) => O,): NonNullable<O>[] { const ret: NonNullable<O>[] = [];
for (const element of array) { const transformedElement = transformer(element);
if (transformedElement !== undefined && transformedElement !== null) { ret.push(transformedElement as NonNullable<O>); } }
return ret;}
std

Version Info

Tagged at
6 months ago