Skip to content

Instantly share code, notes, and snippets.

@JesterXL
Created March 18, 2022 20:54
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 JesterXL/b3b1e0fea0d6719ecd50725f203251b6 to your computer and use it in GitHub Desktop.
Save JesterXL/b3b1e0fea0d6719ecd50725f203251b6 to your computer and use it in GitHub Desktop.
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
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