Skip to content

Instantly share code, notes, and snippets.

@emiflake
Created September 17, 2018 15:23
Show Gist options
  • Save emiflake/6e30aa768e65e5381c57301b62abc94a to your computer and use it in GitHub Desktop.
Save emiflake/6e30aa768e65e5381c57301b62abc94a to your computer and use it in GitHub Desktop.
Monadic Maybes using Promises! (In TypeScript)
interface Maybe<T> {
isJust: Boolean;
isNothing: Boolean;
}
class Just<T> implements Maybe<T> {
constructor(private value: T) {
}
isJust: true;
isNothing: false;
getValue(): T {
return this.value;
}
}
class Nothing<T> implements Maybe<T> {
isJust: false;
isNothing: true;
}
function safeGet<V, K>(dict: { [key: string]: V }, key: K): Maybe<V> {
const val = dict[key.toString()];
return val ? new Just<V>(val) : new Nothing<V>();
}
function toPromise<T>(v: Maybe<T>): Promise<T> {
return new Promise((resolve, reject) => {
if (v instanceof Just) {
resolve(v.getValue());
} else {
reject("Was nothing");
}
});
}
const dict = { a: 'foo', b: 'bar', c: 'baz' };
const promises = ['a', 'b', 'c'].map(x => toPromise(safeGet(dict, x)));
Promise.all(promises).then(all => {
console.log(all);
}).catch(err => {
console.error(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment