Skip to content

Instantly share code, notes, and snippets.

@samatt
Last active May 24, 2018 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samatt/b826b1231e0d0ca66973485b0abd1d65 to your computer and use it in GitHub Desktop.
Save samatt/b826b1231e0d0ca66973485b0abd1d65 to your computer and use it in GitHub Desktop.
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();
@samatt
Copy link
Author

samatt commented May 24, 2018

Promise { }
1

@thejefflarson
Copy link

Try:

async function unsafeToSafe() {
  return (await R(new Promise((_, reject) => reject("blowup"))))
    .or(new Ok(2))
    .unwrap();
}

unsafeToSafe().then(x => console.log(x))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment