Skip to content

Instantly share code, notes, and snippets.

@ericzakariasson
Last active September 15, 2021 08:18
Show Gist options
  • Save ericzakariasson/4ce6c4a48050f8a8589502c6db0043e7 to your computer and use it in GitHub Desktop.
Save ericzakariasson/4ce6c4a48050f8a8589502c6db0043e7 to your computer and use it in GitHub Desktop.
class InternalError extends Error {}
type Predicate<T> = (item: T) => boolean;
function single<T>(array: T[], predicate?: Predicate<T>) {
const items = predicate ? array.filter(predicate) : array;
if (items.length !== 1) {
throw new InternalError("Array does not contain exactly one item");
}
return items[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment