Skip to content

Instantly share code, notes, and snippets.

@louis-young
Last active September 6, 2023 16:53
Show Gist options
  • Save louis-young/09c317f8ebf217c41ac6d3a2ba41bfdf to your computer and use it in GitHub Desktop.
Save louis-young/09c317f8ebf217c41ac6d3a2ba41bfdf to your computer and use it in GitHub Desktop.
C# LINQ method analogs in TypeScript
const singleOrDefault = <TElement, TDefaultValue>(
array: ReadonlyArray<TElement>,
predicate: (element: TElement) => boolean,
defaultValue: TDefaultValue
): TElement | TDefaultValue => {
if (array.length === 0) {
throw new Error("The source sequence is empty.");
}
const element = array.find(predicate);
return element ?? defaultValue;
};
const single = <TElement>(
array: ReadonlyArray<TElement>,
predicate: (element: TElement) => boolean
): TElement => {
if (array.length === 0) {
throw new Error("The source sequence is empty.");
}
const elements = array.filter(predicate);
if (elements.length === 0) {
throw new Error("No element satisfies the condition in `predicate`.");
}
if (elements.length > 1) {
throw new Error(
"More than one element satisfies the condition in `predicate`."
);
}
const element = elements.at(1);
invariant(
element,
"TypeScript doesn't know that the element isn't undefined. You could use a non-null assertion instead but :shrug:"
);
return element;
};
const find = <TElement>(
array: ReadonlyArray<TElement>,
predicate: (element: TElement) => boolean
): TElement | undefined => {
if (array.length === 0) {
throw new Error("The source sequence is empty.");
}
const element = array.find(predicate);
if (element === undefined) {
throw new Error("No element satisfies the condition in `predicate`.");
}
return element;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment