Last active
May 5, 2018 16:18
-
-
Save ENvironmentSet/d1036491669360954ce5cdcae4b8aff0 to your computer and use it in GitHub Desktop.
10분이면 여러분도 Future Monad를 만들 수 있습니다.
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
module.exports = ( () => { | |
const STATE = { PENDING: 0, DONE: 1, FAIL: 2}; | |
class Future { | |
constructor(worker) { | |
this.state = STATE.PENDING; | |
this.value = undefined; | |
this.handlers = []; | |
try{ | |
worker(Future.resolver(this), Future.rejector(this)); | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
static resolver(future) { | |
return (value) => { | |
if(future.state !== STATE.PENDING) throw new Error('this Future is already end'); | |
future.state = STATE.DONE; | |
future.value = value; | |
for(let handler of future.handlers) { | |
try { | |
setImmediate(() => handler(value)); | |
} catch(handleError) { | |
console.error(handleError); | |
} | |
} | |
}; | |
} | |
static rejector(future) { | |
return (error) => { | |
if(future.state !== STATE.PENDING) throw new new Error('this Future is already end'); | |
future.state = STATE.FAIL; | |
future.value = error; | |
for(let handler of future.handlers) { | |
try { | |
setImmediate(() => handler(error)); | |
} catch(handleError) { | |
console.error(handleError); | |
} | |
} | |
}; | |
} | |
ready(handler) { | |
let resultFuture = new Future( resolver => { | |
if(this.state === STATE.DONE) setImmediate(() => resolver(handler(this.value))); | |
else this.handlers.push(value => resolver(handler(value))); | |
}); | |
return resultFuture; | |
} | |
} | |
return { | |
STATE: Object.assign(STATE), | |
Future | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment