deno.land / std@0.166.0 / collections / find_single.ts

find_single.ts
نووسراو ببینە
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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.// This module is browser compatible.
/** * Returns an element if and only if that element is the only one matching the given condition. Returns `undefined` otherwise. * * Example: * * ```ts * import { findSingle } from "https://deno.land/std@$STD_VERSION/collections/find_single.ts"; * import { assertEquals } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts"; * * const bookings = [ * { month: 'January', active: false }, * { month: 'March', active: false }, * { month: 'June', active: true }, * ]; * const activeBooking = findSingle(bookings, (it) => it.active); * const inactiveBooking = findSingle(bookings, (it) => !it.active); * * assertEquals(activeBooking, { month: "June", active: true }); * assertEquals(inactiveBooking, undefined); // there are two applicable items * ``` */export function findSingle<T>( array: readonly T[], predicate: (el: T) => boolean,): T | undefined { let match: T | undefined = undefined; let found = false; for (const element of array) { if (predicate(element)) { if (found) { return undefined; } found = true; match = element; } }
return match;}
std
Deno standard library
GitHub Repositorydenoland/deno_std
GitHub Stars
2458

Version Info

Tagged at
2 months ago