UNPKG

@bitty/maybe

Version:
103 lines (91 loc) 3.33 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Maybe = {})); })(this, (function (exports) { 'use strict'; var None = { _kind: 'None', alt: function (fn) { return fn(); }, map: function () { return None; }, then: function () { return None; }, chain: function () { return None; }, isNone: function () { return true; }, isSome: function () { return false; }, match: function (_a) { var none = _a.none; return none(); }, fold: function (onLeft) { return onLeft(); }, getOrElse: function (onLeft) { return onLeft(); }, unwrap: function () { return null; }, }; function isMaybe(value) { return (value === null || value === void 0 ? void 0 : value._kind) === 'Some' || value === None; } function Some(value) { return { _kind: 'Some', alt: function () { return Some(value); }, map: function (fn) { return Some(fn(value)); }, then: function (fn) { var valueOrMaybe = fn(value); return isMaybe(valueOrMaybe) ? valueOrMaybe : Some(valueOrMaybe); }, chain: function (fn) { return fn(value); }, match: function (_a) { var some = _a.some; return some(value); }, fold: function (_, onSome) { return onSome(value); }, isNone: function () { return false; }, isSome: function () { return true; }, getOrElse: function () { return value; }, unwrap: function () { return value; }, }; } /** * Union of values that is considered false when converted to `Boolean`. * @see {@link https://developer.mozilla.org/en-US/docs/Glossary/Falsy}. * @typedef {false | void | '' | 0 | 0n | null | undefined} Falsy */ /** * Check if value is falsy (`""`, `null`, `false`, `0`, `NaN` or `undefined`). * @param {*} value - The value that will be checked. * @returns {Boolean} */ function isFalsy(value) { return !value; } function fromFalsy(value) { return isFalsy(value) ? None : Some(value); } /** * Check if value is nullish (`void`, `null` or `undefined`). * @param {*} value - Value that will be checked. * @returns {Boolean} */ function isNullish(value) { return value == null; } function fromNullish(value) { return isNullish(value) ? None : Some(value); } function fromPredicate(predicate) { return function (value) { return (predicate(value) ? Some(value) : None); }; } function tryCatch(fn) { try { return Some(fn()); } catch (error) { return None; } } exports.None = None; exports.Some = Some; exports.fromFalsy = fromFalsy; exports.fromNullish = fromNullish; exports.fromPredicate = fromPredicate; exports.tryCatch = tryCatch; })); //# sourceMappingURL=Maybe.umd.js.map