UNPKG

maybe-not

Version:

Maybe you should use this instead of nullable types..

114 lines 3.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Maybe = void 0; class Maybe { constructor(value) { this.value = value; } static just(val) { if (val === undefined || val === null) { throw new TypeError('Value passed to just must exist!'); } return new Maybe(val); } static nothing() { return new Maybe(); } static maybe(val) { if (val === undefined || val === null) { return Maybe.nothing(); } return Maybe.just(val); } static join(nestedMaybe) { return nestedMaybe.withDefault(Maybe.nothing()); } static sequence(arr) { return arr.reduce((acc, val) => { return acc.bind(arr => val.map(item => arr.concat(item))); }, Maybe.just([])); } static traverse(fn, arr) { return Maybe.sequence(arr).map(items => items.map(fn)); } static justMap(fn, arr) { return arr.reduce((acc, item) => { const mValue = fn(item); return mValue.value !== undefined ? acc.concat(mValue.value) : acc; }, []); } static filterSomethings(arr) { return arr.reduce((acc, xM) => { if (xM.value) { acc.push(xM.value); } return acc; }, []); } static lift(fn) { return mX => mX.map(fn); } static lift2(fn) { return (mX, mY) => Maybe.sequence([mX, mY]).map(ms => fn(ms[0], ms[1])); } static lift3(fn) { return (mX, mY, mZ) => Maybe.sequence([mX, mY, mZ]).map(ms => fn(ms[0], ms[1], ms[2])); } static toPromise(maybe) { if (maybe.hasSomething) { return Promise.resolve(maybe.value); } else { return Promise.reject(); } } map(fn) { if (this.value !== undefined) { return Maybe.maybe(fn(this.value)); } return Maybe.nothing(); } asyncMap(fn) { if (this.value !== undefined) { return fn(this.value).then(x => { if (x === undefined || x === null) { throw 'Promise Conversion from a Maybe.Nothing'; } return x; }); } return Promise.reject(); } alt(elseValue) { return this.value !== undefined ? this : elseValue; } altMap(elseFn) { return this.value !== undefined ? this : elseFn(); } ap(mFn) { return mFn.bind(fn => this.map(fn)); } bind(fn) { return Maybe.join(this.map(fn)); } withDefault(fallback) { return this.value !== undefined ? this.value : fallback; } withDefaultFn(fallbackFn) { return this.value !== undefined ? this.value : fallbackFn(); } get hasNothing() { return this.value === undefined; } get hasSomething() { return !this.hasNothing; } unsafeElse(fn) { if (this.hasNothing) { fn(); } } } exports.Maybe = Maybe; Maybe.of = Maybe.maybe; //# sourceMappingURL=maybe-not.js.map