Last active
May 24, 2018 16:49
-
-
Save samatt/b826b1231e0d0ca66973485b0abd1d65 to your computer and use it in GitHub Desktop.
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
class Thing { | |
constructor(val) { | |
this.val = val; | |
} | |
unwrap() { | |
throw "unimplemented!"; | |
} | |
is_ok() { | |
throw "unimplemented!"; | |
} | |
is_err() { | |
throw "unimplemented!"; | |
} | |
} | |
class Ok extends Thing { | |
constructor(val) { | |
super(val); | |
} | |
unwrap() { | |
return this.val; | |
} | |
is_ok() { | |
console.log("HERE"); | |
return true; | |
} | |
is_err() { | |
false; | |
} | |
} | |
class Err extends Thing { | |
constructor(val) { | |
super(val); | |
} | |
unwrap() { | |
throw this.val; | |
} | |
is_ok() { | |
return false; | |
} | |
is_err() { | |
return true; | |
} | |
} | |
class Result { | |
constructor(val) { | |
this.val = val; | |
} | |
and(val) { | |
if (this.val.is_ok() && val.is_ok()) { | |
return new Result(val); | |
} else { | |
if (this.val.is_err()) { | |
return new Result(this.val); | |
} else if (val.is_err()) { | |
return new Result(val); | |
} | |
} | |
} | |
and_then(cb) { | |
if (this.val.is_ok()) { | |
return cb(this.val); | |
} else { | |
return new Result(this.val); | |
} | |
} | |
or(val) { | |
if (this.val.is_ok()) { | |
return new Result(this.val); | |
} else { | |
return new Result(val); | |
} | |
} | |
unwrap() { | |
return this.val.unwrap(); | |
} | |
static async wrap(promise) { | |
try { | |
return new Result(new Ok(await promise)); | |
} catch (e) { | |
return new Result(new Err(e)); | |
} | |
} | |
} | |
const R = Result.wrap; | |
// examples | |
// const throws = new Promise((_, reject) => reject("blowup")); | |
const one = new Promise((r, rej) => r(1)); | |
const two = new Promise(r => 2); | |
// async function unsafeThing() { | |
// await R(throws).unwrap(); | |
// } | |
async function safe() { | |
let x = await R(one); | |
console.log(x.unwrap()); | |
} // 2 | |
/*async function unsafeToSafe() { | |
await R(throws) | |
.or(new Ok(2)) | |
.unwrap(); | |
} // 2*/ | |
// unsafeThing(); | |
console.log(safe()); | |
// unsafeToSafe(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try: