2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-09-18 18:29:29 +00:00
|
|
|
// This module is browser compatible.
|
2021-08-31 07:30:57 +00:00
|
|
|
|
|
|
|
/**
|
2022-11-25 11:40:23 +00:00
|
|
|
* Applies the given selector to elements in the given array until a value is
|
|
|
|
* produced that is neither `null` nor `undefined` and returns that value.
|
|
|
|
* Returns `undefined` if no such value is produced.
|
2021-08-31 07:30:57 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the elements in the input array.
|
|
|
|
* @typeParam O The type of the value produced by the selector function.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param array The array to select a value from.
|
|
|
|
* @param selector The function to extract a value from an element.
|
|
|
|
*
|
|
|
|
* @returns The first non-`null` and non-`undefined` value produced by the
|
|
|
|
* selector function, or `undefined` if no such value is produced.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2021-08-31 07:30:57 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { firstNotNullishOf } from "@std/collections/first-not-nullish-of";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2021-08-31 07:30:57 +00:00
|
|
|
*
|
|
|
|
* const tables = [
|
2022-11-25 11:40:23 +00:00
|
|
|
* { number: 11, order: null },
|
|
|
|
* { number: 12, order: "Soup" },
|
|
|
|
* { number: 13, order: "Salad" },
|
|
|
|
* ];
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
2024-05-07 07:11:55 +00:00
|
|
|
* const nextOrder = firstNotNullishOf(tables, (table) => table.order);
|
2021-08-31 07:30:57 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* assertEquals(nextOrder, "Soup");
|
2021-08-31 07:30:57 +00:00
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function firstNotNullishOf<T, O>(
|
2023-05-30 23:48:21 +00:00
|
|
|
array: Iterable<T>,
|
2021-08-31 07:30:57 +00:00
|
|
|
selector: (item: T) => O | undefined | null,
|
|
|
|
): NonNullable<O> | undefined {
|
|
|
|
for (const current of array) {
|
|
|
|
const selected = selector(current);
|
|
|
|
|
|
|
|
if (selected !== null && selected !== undefined) {
|
|
|
|
return selected as NonNullable<O>;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return undefined;
|
|
|
|
}
|