@stnekroman/tstools
Version:
Set of handy tools for TypeScript development
102 lines (101 loc) • 2.68 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Optional = void 0;
const Objects_1 = require("../Objects");
const NoSuchElementException_1 = require("./NoSuchElementException");
class Optional {
constructor(value) {
this.value = value;
}
static of(value) {
if (Objects_1.Objects.isNotNullOrUndefined(value)) {
return new Optional(value);
}
else {
return Optional.EMPTY;
}
}
static empty() {
return Optional.EMPTY;
}
get() {
if (this.isPresent()) {
return this.value;
}
throw new NoSuchElementException_1.NoSuchElementException('No value present');
}
isPresent() {
return Objects_1.Objects.isNotNullOrUndefined(this.value);
}
isEmpty() {
return Objects_1.Objects.isNullOrUndefined(this.value);
}
filter(filterFn) {
if (this.isEmpty()) {
return this;
}
else {
return filterFn(this.value) ? this : Optional.EMPTY;
}
}
map(mapper) {
if (this.isEmpty()) {
return Optional.EMPTY;
}
else {
return Optional.of(mapper(this.value));
}
}
flatMap(mapper) {
if (this.isEmpty()) {
return Optional.EMPTY;
}
else {
return mapper(this.value);
}
}
mapAsync(mapper) {
if (this.isEmpty()) {
return Promise.resolve(Optional.EMPTY);
}
else {
return mapper(this.value).then((r) => Optional.of(r));
}
}
or(provider) {
if (this.isPresent()) {
return this;
}
else {
return provider();
}
}
orElse(other) {
return this.isPresent() ? this.value : other;
}
orElseGet(provider) {
return this.isPresent() ? this.value : provider();
}
orElseThrow(provider) {
if (this.isEmpty()) {
throw provider ? provider() : new NoSuchElementException_1.NoSuchElementException('No value present');
}
return this.value;
}
toString() {
return this.isPresent() ? `Optional[${this.value}]` : 'Optional.empty';
}
equals(another) {
if (this == another ||
(this.isEmpty() && another.isEmpty()) ||
(isNaN(this.value) && isNaN(another.value))) {
return true;
}
return this.value === another.value;
}
property(key) {
return Optional.of(this.value[key]);
}
}
exports.Optional = Optional;
Optional.EMPTY = new Optional(undefined);