Created
November 18, 2018 03:54
-
-
Save baetheus/6faef25ee3c06279b135d3c92cf01be1 to your computer and use it in GitHub Desktop.
Cascade
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
| // A function that operates like a ternary operator but can be lazy | |
| export type CascadePair<S, C = boolean> = [C, S]; | |
| export const cascade = <T>(...cases: CascadePair<T>[]) => { | |
| const match = cases.find(c => c[0]); | |
| return match !== undefined ? match[1] : undefined; | |
| }; | |
| export const cascadeOrElse = <T>(def: T, ...cases: CascadePair<T>[]) => { | |
| const match = cascade(...cases); | |
| return match !== undefined ? match : def; | |
| }; | |
| export const lazyCascade = <T>(...cases: CascadePair<T, () => boolean>[]) => { | |
| const match = cases.find(c => c[0]()); | |
| return match !== undefined ? match[1] : undefined; | |
| }; | |
| export const lazyCascadeOrElse = <T>( | |
| def: T, | |
| ...cases: CascadePair<T, () => boolean>[] | |
| ) => { | |
| const match = lazyCascade(...cases); | |
| return match !== undefined ? match : def; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment