Created
September 17, 2018 15:23
-
-
Save emiflake/6e30aa768e65e5381c57301b62abc94a to your computer and use it in GitHub Desktop.
Monadic Maybes using Promises! (In TypeScript)
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
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