@snipsonian/core
Version:
Core/base reusable javascript code snippets
41 lines (40 loc) • 932 B
JavaScript
import isNull from '../is/isNull';
import isUndefined from '../is/isUndefined';
export class Maybe {
constructor(value) {
this.value = value;
}
static of(value) {
return new Maybe(value);
}
static nothing() {
return new Maybe(null);
}
isNothing() {
return isNull(this.value) || isUndefined(this.value);
}
map(mapper) {
return this.isNothing()
? Maybe.nothing()
: Maybe.of(mapper(this.value));
}
flatMap(mapper) {
return this.isNothing()
? Maybe.nothing()
: mapper(this.value);
}
getOrElse(elseValue) {
return this.isNothing()
? elseValue
: this.value;
}
getOrNull() {
return this.getOrElse(null);
}
getOrEmptyArray() {
return this.getOrElse([]);
}
getOrEmptyObject() {
return this.getOrElse({});
}
}