UNPKG

declarative-js

Version:

_declarative-js_ is modern JavaScript library, that helps to: - tackle array transformation with built in JavaScript array api (e.g. `array.filter(toBe.unique())`), - provide a type-level solution for representing optional values instead of null referen

59 lines (58 loc) 1.68 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ToArray_1 = require("../internal/ToArray"); exports.Optional = OptionalImpl; function OptionalImpl(value) { this.value = value; } OptionalImpl.prototype = { orElse: function (value) { return this.isPresent() ? this.value : value; }, isPresent: function () { return this.value != undefined; }, isAbsent: function () { return this.value == undefined; }, orElseGet: function (supplier) { return this.isPresent() ? this.value : supplier(); }, orElseThrow: function (errorMessage) { if (!this.isPresent()) { throw new Error(errorMessage); } return this.value; }, ifPresent: function (consumer) { if (this.isPresent()) { consumer(); } }, ifAbsent: function (consumer) { if (this.isAbsent()) { consumer(); } }, get: function () { if (this.value == undefined) { throw new Error('Value is not defined'); } return this.value; }, map: function (mapper) { return this.isPresent() ? new exports.Optional(mapper(this.value)) : new exports.Optional(); }, filter: function (predicate) { if (this.isPresent()) { return predicate(this.value) ? this : new exports.Optional(); } return new exports.Optional(); }, toArray: function () { return ToArray_1.toArray(this.value); } }; exports.optional = function (value) { return new exports.Optional(value); };