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-09-12 15:04:15 +00:00
|
|
|
|
|
|
|
/**
|
2022-11-25 11:40:23 +00:00
|
|
|
* Returns an element if and only if that element is the only one matching the
|
|
|
|
* given condition. Returns `undefined` otherwise.
|
2021-09-12 15:04:15 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the elements in the input array.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param array The array to find a single element in.
|
|
|
|
* @param predicate The function to test each element for a condition.
|
|
|
|
*
|
|
|
|
* @returns The single element that matches the given condition or `undefined`
|
|
|
|
* if there are zero or more than one matching elements.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2021-09-12 15:04:15 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { findSingle } from "@std/collections/find-single";
|
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-09-12 15:04:15 +00:00
|
|
|
*
|
|
|
|
* const bookings = [
|
2022-11-25 11:40:23 +00:00
|
|
|
* { month: "January", active: false },
|
|
|
|
* { month: "March", active: false },
|
|
|
|
* { month: "June", active: true },
|
2021-09-12 15:04:15 +00:00
|
|
|
* ];
|
2024-05-06 07:51:20 +00:00
|
|
|
* const activeBooking = findSingle(bookings, (booking) => booking.active);
|
|
|
|
* const inactiveBooking = findSingle(bookings, (booking) => !booking.active);
|
2021-09-12 15:04:15 +00:00
|
|
|
*
|
|
|
|
* assertEquals(activeBooking, { month: "June", active: true });
|
2024-05-06 07:51:20 +00:00
|
|
|
* assertEquals(inactiveBooking, undefined); // There are two applicable items
|
2021-09-12 15:04:15 +00:00
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function findSingle<T>(
|
2023-05-30 23:48:21 +00:00
|
|
|
array: Iterable<T>,
|
2021-10-27 03:18:15 +00:00
|
|
|
predicate: (el: T) => boolean,
|
2021-09-12 15:04:15 +00:00
|
|
|
): T | undefined {
|
2024-05-07 07:11:55 +00:00
|
|
|
let match: T | undefined;
|
2021-09-12 15:04:15 +00:00
|
|
|
let found = false;
|
|
|
|
for (const element of array) {
|
|
|
|
if (predicate(element)) {
|
2024-05-07 07:11:55 +00:00
|
|
|
if (found) return undefined;
|
2021-09-12 15:04:15 +00:00
|
|
|
found = true;
|
|
|
|
match = element;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return match;
|
|
|
|
}
|