Last active
May 22, 2021 14:06
-
-
Save harbirchahal/b5d47dd0d8f01c8108c97d8a0c807eab to your computer and use it in GitHub Desktop.
Try functional data type
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 Try { | |
constructor(val) { | |
this._val = val; | |
} | |
static of(fn) { | |
try { | |
return new Success(fn()); | |
} catch (err) { | |
return new Failure(err); | |
} | |
} | |
map(fn) { | |
return Try.of(() => fn(this._val)); | |
} | |
} | |
class Success extends Try { | |
getOrElse(other) { | |
return this._val; | |
} | |
getOrElseThrow() { | |
return this._val; | |
} | |
} | |
class Failure extends Try { | |
map(fn) { | |
return this; | |
} | |
getOrElse(other) { | |
return other; | |
} | |
getOrElseThrow() { | |
if(this._val !== null) { | |
throw this._val; | |
} | |
} | |
} | |
// Main | |
let record = Try.of(() => findRecordById('123')) | |
.map(processRecord) | |
.getOrElse(new Record('123', 'RecordA')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment