UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 2.87 kB
{"version":3,"file":"single-CXest5gH.cjs","names":["filter"],"sources":["../src/functions/single/single.ts"],"sourcesContent":["import type { Maybe } from '../../types';\nimport { filter } from '../_internal/filterIterable';\n\n/**\n * Returns the single element of an iterable, or `undefined` if there are zero or multiple matches.\n * @param source The iterable to search.\n * @returns The single element, or `undefined` if there are zero or multiple matches.\n * @example\n * ```ts\n * single([1, 2, 3]); // undefined (because there are multiple elements in the array)\n * single([1]); // 1 (because there's only one element in the array)\n * ```\n */\nexport function single<T>(source: Maybe<Iterable<T>>): T | undefined;\n/**\n * Returns the single element of an iterable that satisfies a predicate.\n * @param source The iterable to search.\n * @param predicate The predicate function used to determine if an element is a match.\n * @returns The single matching element, or `undefined` if there are zero or multiple matches.\n * @example\n * ```ts\n * single([1, 2, 3], x => x % 2 === 0); // 2 (because there's only one even number in the array)\n * single([1, 2, 3], x => x >= 1); // undefined (because there are multiple matches for the predicate)\n * ```\n */\nexport function single<T>(\n source: Maybe<Iterable<T>>,\n predicate?: (value: T, index: number) => boolean\n): T | undefined;\n/**\n * Returns the single element of an iterable that satisfies a predicate.\n * @param source The iterable to search.\n * @param predicate The predicate function used to determine if an element is a match.\n * @returns The single matching element, or undefined if there are zero or multiple matches.\n * @example\n * ```ts\n * interface Person {\n * name: string;\n * age: number;\n * }\n *\n * const people: (Person | number)[] = [\n * { name: 'Alice', age: 30 },\n * 50,\n * ];\n *\n * declare function isPerson(value: unknown): value is Person;\n *\n * const result = single(people, isPerson); // { name: 'Alice', age: 30 }\n * // ^? Person | undefined\n * ```\n */\nexport function single<T, S>(\n source: Maybe<Iterable<T>>,\n predicate?: (value: S, index: number) => value is S\n): S | undefined;\n/**\n * Implementation for all overloads.\n * @param source The iterable to search.\n * @param predicate The predicate function used to determine if an element is a match.\n * @returns The single matching element, or undefined if there are zero or multiple matches.\n */\nexport function single<T>(\n source: Maybe<Iterable<T>>,\n predicate?: (value: T, index: number) => boolean\n): T | undefined {\n const relevantItems = filter(source, predicate);\n return relevantItems?.length === 1 ? relevantItems[0] : undefined;\n}\n"],"mappings":";;;;;;;;;AA8DA,SAAgB,OACd,QACA,WACe;CACf,MAAM,gBAAgBA,8BAAO,QAAQ,UAAU;AAC/C,QAAO,eAAe,WAAW,IAAI,cAAc,KAAK"}