Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Last active May 22, 2021 14:06
Show Gist options
  • Save harbirchahal/b5d47dd0d8f01c8108c97d8a0c807eab to your computer and use it in GitHub Desktop.
Save harbirchahal/b5d47dd0d8f01c8108c97d8a0c807eab to your computer and use it in GitHub Desktop.
Try functional data type
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