Created
May 15, 2021 03:15
-
-
Save buttercubz/f1a471cfd3d4c5a78c28ea955207964f to your computer and use it in GitHub Desktop.
Match function
This file contains 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
export type Fn = () => any; | |
export function Match<T extends any>(data: T) { | |
const cases: Array<{ condition: any; action?: Fn }> = []; | |
let once = true; | |
return { | |
case(condition: T, action: Fn) { | |
cases.push({ condition, action }); | |
return this; | |
}, | |
default(action?: Fn) { | |
if (once) { | |
cases.push({ condition: "DEFAULT", action }); | |
once = false; | |
} | |
return { | |
Value() { | |
const value = cases | |
.map(({ action, condition }) => { | |
if (condition === data) { | |
return action?.(); | |
} | |
}) | |
.filter((val) => val); | |
const none = cases.filter(({ condition }) => condition === "DEFAULT"); | |
return value.length | |
? value.shift() | |
: none.shift()?.action?.() ?? null; | |
}, | |
}; | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment