All files / collections / unstable_find_single.ts

100.00% Branches 5/5
100.00% Lines 15/15
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
53
54
55
56
57
58
59
60
61
62
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x3
x3
 
x7
x7
x7
x7
x18
x23
x27
x27
x27
x18
 
x10
x7





























































// Copyright 2018-2026 the Deno authors. 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.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @typeParam T The type of the elements in the input array.
 *
 * @param array The array to find a single element in.
 * @param predicate The function to test each element for a condition. The
 * function receives the element and its index.
 *
 * @returns The single element that matches the given condition or `undefined`
 * if there are zero or more than one matching elements.
 *
 * @example Basic usage
 * ```ts
 * import { findSingle } from "@std/collections/unstable-find-single";
 * import { assertEquals } from "@std/assert";
 *
 * const bookings = [
 *   { month: "January", active: false },
 *   { month: "March", active: false },
 *   { month: "June", active: true },
 * ];
 * const activeBooking = findSingle(bookings, (booking) => booking.active);
 * const inactiveBooking = findSingle(bookings, (booking) => !booking.active);
 *
 * assertEquals(activeBooking, { month: "June", active: true });
 * assertEquals(inactiveBooking, undefined); // There are two applicable items
 * ```
 *
 * @example Using the index parameter
 * ```ts
 * import { findSingle } from "@std/collections/unstable-find-single";
 * import { assertEquals } from "@std/assert";
 *
 * const array = [9, 12, 13];
 * const result = findSingle(array, (_, index) => index === 1);
 *
 * assertEquals(result, 12);
 * ```
 */
export function findSingle<T>(
  array: Iterable<T>,
  predicate: (el: T, index: number) => boolean,
): T | undefined {
  let match: T | undefined;
  let found = false;
  let index = 0;
  for (const element of array) {
    if (predicate(element, index++)) {
      if (found) return undefined;
      found = true;
      match = element;
    }
  }

  return match;
}