findSingle

import { findSingle } from "jsr:@ende/collections";

function

function findSingle<T>(array: Iterable<T>, predicate: (el: T, index: number) => boolean): T | undefined

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

array: Iterable<T>

The array to find a single element in.

predicate: (el: T, index: number) => boolean

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

import { findSingle } from "@ende/collections/find-single";
import { assertEquals } from "@ende/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

import { findSingle } from "@ende/collections/find-single";
import { assertEquals } from "@ende/assert";

const array = [9, 12, 13];
const result = findSingle(array, (_, index) => index === 1);

assertEquals(result, 12);

Source