Skip to content

Instantly share code, notes, and snippets.

@lbialy
Created November 5, 2015 08:19
Show Gist options
  • Save lbialy/98fa5ad25554d6296f55 to your computer and use it in GitHub Desktop.
Save lbialy/98fa5ad25554d6296f55 to your computer and use it in GitHub Desktop.
Simplified tspatternmatching, updated from simplified form from Michał Załęcki: https://gist.github.com/MichalZalecki/e4119f95c0b7fba2d51c
class MatchError extends Error {
}
function match<T, S>(value:T) {
let result:(_:T)=>S;
const context = {
caseOf(predicate:(value:T) => boolean, payload:(_:T)=>S) {
if (!result && predicate(value)) result = payload;
return context;
},
_(payload:(_:T)=>S) {
if (!result) result = payload;
return context;
},
resolve(): S {
if (!result) {
throw new MatchError;
}
return result(value);
}
};
return context;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment