Last active
September 6, 2023 16:53
-
-
Save louis-young/09c317f8ebf217c41ac6d3a2ba41bfdf to your computer and use it in GitHub Desktop.
C# LINQ method analogs in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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