Skip to content

Instantly share code, notes, and snippets.

@buttercubz
Created May 15, 2021 03:15
Show Gist options
  • Save buttercubz/f1a471cfd3d4c5a78c28ea955207964f to your computer and use it in GitHub Desktop.
Save buttercubz/f1a471cfd3d4c5a78c28ea955207964f to your computer and use it in GitHub Desktop.
Match function
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