typescript-nullsafe
Version:
70 lines • 1.81 kB
JavaScript
import { hasNoValue, hasValue } from "../hasValue";
export class Optional {
constructor(value) {
this.value = value;
}
filter(filter) {
if (this.isPresent()) {
return filter(this.value) ? this : Optional.empty();
}
return this;
}
flatMap(mapper) {
if (this.isPresent()) {
return mapper(this.value);
}
return Optional.empty();
}
map(mapper) {
if (this.isPresent()) {
return Optional.ofNullable(mapper(this.value));
}
return Optional.empty();
}
get() {
if (this.isEmpty()) {
throw new Error("The value is null or undefined or Number.NAN!");
}
return this.value;
}
ifPresent(consumer) {
if (this.isPresent())
consumer(this.value);
}
isPresent() {
return hasValue(this.value);
}
isEmpty() {
return hasNoValue(this.value);
}
orElse(defaultValue) {
if (this.isPresent()) {
return this.value;
}
return defaultValue;
}
orElseGet(provider) {
if (this.isPresent()) {
return this.value;
}
return provider();
}
ifPresentOrElse(consumer, orElseConsumer) {
if (this.isPresent())
consumer(this.value);
else
orElseConsumer();
}
static ofNullable(data) {
return new Optional(data);
}
static of(data) {
if (hasNoValue(data))
throw new Error("Value should never be null nor undefined!");
return Optional.ofNullable(data);
}
static empty() {
return new Optional(null);
}
}
//# sourceMappingURL=Optional.js.map