UNPKG

@buession/prototype

Version:

A native object extension framework for Javascript.

70 lines (69 loc) 1.79 kB
"use strict"; /** * Optional 对象 */ class Optional { /** * 构造函数 * * @param value T 类型的值 */ constructor(value) { this.value = value; } /** * 返回一个指定 T 类型的值的 Optional 实例 * * @param value T 类型的值 * @return T 类型的值的 Optional 实例 */ static of(value) { return new Optional(value); } /** * 如果为非 null 或 undefined,返回 Optional 描述的指定值的实例,否则返回空的 Optional 实例 * * @param value T 类型的值 * @return T 类型的值的 Optional 实例,或空的 Optional 实例 */ static ofNullable(value) { return Object.isUndefinedOrNull(value) ? Optional.empty() : new Optional(value); } /** * 返回空的 Optional 实例 * * @return 空的 Optional 实例 */ static empty() { return new Optional(null); } /** * 如果 value 不为 null 或 undefined,则返回 value 的值;否则抛出异常 * * @return Optional 中包含这个值 */ get() { if (this.value === null || typeof this.value === "undefined") { throw "No value present"; } return this.value; } /** * 如果 value 不为 null 或 undefined,则返回 value 的值;否则返回 other * * @param other 其它值 * @return value 不为 null 或 undefined,则返回 value 的值;否则返回 other */ orElse(other) { return Object.isUndefinedOrNull(this.value) ? other : this.value; } /** * 如果 value 不为 null 或 undefined,则返回 true;否则返回 false * * @return value 不为 null 或 undefined,则返回 true;否则返回 false */ isPresent() { return Object.isUndefinedOrNull(this.value) === false; } } window.Optional = Optional;