Last active
October 8, 2017 19:03
-
-
Save ulve/3807e86728a1642e8587753a61903e54 to your computer and use it in GitHub Desktop.
Future
This file contains hidden or 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
// simple | |
const future = f => ({ | |
fork: g => f(g), | |
map: g => future(k => f(l => k(g(l)))), | |
flatMap: g => future(k => f(l => g(l).apply(k))) | |
}) | |
const getHttp = callback => { | |
const id = Math.floor(Math.random() * 5000 + 1000) | |
setTimeout(() => callback(`hej ${id}`), id) | |
} | |
const mapping = (s:string) => `MAPPING(${s})` | |
const midway = future(getHttp).map(mapping) | |
const final = midway.map(x => `IGEN(${x})`) | |
// With reject | |
interface IFuture<T, U> { | |
of(U): IFuture<any, U>; | |
reject(T) : IFuture<T, any>; | |
map<V>(a:(U) => V): IFuture<T, V>; | |
fork<T, U>(a:(T) => void, b:(U) => void) : void; | |
} | |
const future2 = <T, U>(f:(a:(T) => void, b:(U) => void) => void) => ({ | |
fork: (rej:(a:(T) => void) => void, res:(b:(U) => void) => void) => f(rej, res), | |
of: (x:U) => future2((_, res) => res(x)), | |
reject: (x:T) => future2((rej, _) => rej(x)), | |
map: <V>(g:(a:U) => V) : IFuture<T, V> => future2((rej, res) => f(a => rej(a), b => res(g(b)))) | |
}) | |
const getHttp2 = (rej:(string) => void, res: (string) => void) => { | |
const id = Math.floor(Math.random() * 1000 + 1000) | |
setTimeout(() => (id % 2 == 0) ? | |
rej(`det gick åt skogen efter ${id} ms`) : | |
res(`det gick bra efter ${id} ms`) , id) | |
} | |
const withreject : IFuture<string, string> = future2(getHttp2).map(x => x + 'xxx').map(y => 'yyy' + y) | |
withreject.fork(x => console.error('error: ' + x), x => console.log('success: ' + x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment