Function findSingle

  • Returns an element if and only if that element is the only one matching the given condition. Returns undefined otherwise.

    Type Parameters

    • T

      The type of the elements in the input array.

    Parameters

    • array: Iterable<T, any, any>

      The array to find a single element in.

    • predicate: ((el: T) => boolean)

      The function to test each element for a condition.

        • (el): boolean
        • Parameters

          • el: T

          Returns boolean

    Returns T | undefined

    The single element that matches the given condition or undefined if there are zero or more than one matching elements.

    import { findSingle } from "@std/collections/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