Created
March 18, 2022 20:54
-
-
Save JesterXL/b3b1e0fea0d6719ecd50725f203251b6 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
let a = new Ok('uno') | |
let result1 = | |
a.then(i => i + " wat") | |
.then(i => `yeah man: ${i}`) | |
.match({ | |
Ok: i => i, | |
Err: reason => { throw new Error(reason} } | |
}) | |
console.log(result1) // yeah man: uno wat | |
let result2 = | |
a.then(i => i + " wat") | |
.then(() => Err('failed') | |
.then(i => `yeah man: ${i}`) | |
.match({ | |
Ok: i => i, | |
Err: reason => { throw new Error(reason} } | |
}) | |
// Error: failed |
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 Ok { | |
constructor(data) { | |
this.data = data | |
this._type = "Ok" | |
this.then.bind(this) | |
this.match.bind(this) | |
} | |
then(func) { | |
const result = func(this.data) | |
if(result && result._type === 'Ok') { | |
return result | |
} else if(result && result._type === 'Err') { | |
return result | |
} else { | |
return new Ok(result) | |
} | |
} | |
match(obj) { | |
return obj.Ok(this.data) | |
} | |
} | |
class Err { | |
constructor(reason) { | |
this.reason = reason | |
this._type = 'Err' | |
this.then.bind(this) | |
this.match.bind(this) | |
} | |
then() { | |
return this | |
} | |
match(obj) { | |
return obj.Err(this.reason) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment