All files / collections / unstable_map_not_nullish.ts

100.00% Branches 3/3
100.00% Lines 13/13
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
42
43
44
45
46
47
48
49
50
51
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x2
x2
 
x4
x4
 
x4
x12
 
x12
x17
x17
x12
 
x4
x4


















































// Copyright 2018-2026 the Deno authors. 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`.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @typeParam T The type of the elements in the input array.
 * @typeParam O The type of the elements in the output array.
 *
 * @param array The array to map elements from.
 * @param transformer The function to transform each element.
 *
 * @returns A new array with all elements transformed by the given transformer,
 * except the ones that were transformed to `null` or `undefined`.
 *
 * @example Basic usage
 * ```ts
 * import { mapNotNullish } from "@std/collections/unstable-map-not-nullish";
 * import { assertEquals } from "@std/assert";
 *
 * const people = [
 *   { middleName: null },
 *   { middleName: "William" },
 *   { middleName: undefined },
 *   { middleName: "Martha" },
 * ];
 * const foundMiddleNames = mapNotNullish(people, (people) => people.middleName);
 *
 * assertEquals(foundMiddleNames, ["William", "Martha"]);
 * ```
 */
export function mapNotNullish<T, O>(
  array: Iterable<T>,
  transformer: (el: T, index: number) => O,
): NonNullable<O>[] {
  const result: NonNullable<O>[] = [];
  let index = 0;

  for (const element of array) {
    const transformedElement = transformer(element, index++);

    if (transformedElement !== undefined && transformedElement !== null) {
      result.push(transformedElement as NonNullable<O>);
    }
  }

  return result;
}