Skip to content

Instantly share code, notes, and snippets.

@MichalZalecki
Last active November 3, 2015 06:32
Show Gist options
  • Save MichalZalecki/e4119f95c0b7fba2d51c to your computer and use it in GitHub Desktop.
Save MichalZalecki/e4119f95c0b7fba2d51c to your computer and use it in GitHub Desktop.
function match<T, S>(value: T) {
let result: ()=>S;
const context = {
caseOf(fn:(value: T) => boolean, payload: ()=>S) {
if (!result && fn(value)) result = payload;
return context;
},
_(payload: ()=>S) {
if (!result) result = payload;
return context;
},
resolve(): S {
return result();
}
};
return context;
}
const result = match<number, String>(123)
.caseOf(w => w > 200, () => "A")
.caseOf(w => w < 200, () => "B")
.caseOf(w => w < 200, () => "C")
._(() => "D") // wildcard
.resolve(); // "B"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment