UNPKG

better-optional

Version:

Functional "Optionals" solution for JavaScript and TypeScript with async support

55 lines (54 loc) 1.72 kB
const d = (n) => n != null, r = i(void 0); function i(n) { const o = d(n), f = (t) => { if (o) return n; throw t ?? new Error("Value is not present"); }, e = { get: () => f(), valueOf: () => n, or: (t) => o ? e : t, isPresent: () => o, isEmpty: () => !o, orElse: (t) => o ? n : t, orElseGet: (t) => o ? n : t(), orElseGetAsync: async (t) => o ? n : await t(), orElseThrow: (t) => f(t), map: (t) => o ? i(t(n)) : r, mapAsync: async (t) => o ? i(await t(n)) : r, flatMap: (t) => o ? t(n) : r, flatMapAsync: async (t) => o ? await t(n) : r, filter: (t) => o && t(n) ? e : r, filterAsync: async (t) => o && await t(n) ? e : r, ifPresent: (t) => o ? t(n) : void 0, ifPresentAsync: async (t) => o ? await t(n) : void 0, ifPresentOrElse: (t, s) => o ? t(n) : s(), ifPresentOrElseAsync: async (t, s) => o ? await t(n) : await s(), toString: () => o ? c(n.toString()) : l, toLocaleString: () => o ? c(n.toLocaleString()) : l }; return e; } const p = "Optional", c = (n) => `${p}[${n}]`, l = p + ".empty", y = { of: (n) => { if (n != null) return i(n); throw new Error(a("nullish")); }, ofNullish: (n) => i(n), ofNullable: (n) => { if (n !== void 0) return i(n); throw new Error(a("undefined")); }, ofUndefinable: (n) => { if (n !== null) return i(n); throw new Error(a("null")); }, empty: () => r }, a = (n) => `Cannot create an optional value from a ${n} value. ${n === "nullish" ? "If you want to do this on purpose use Optional.ofNullish(). " : ""}If you want to create an empty optional, use Optional.empty() instead.`; export { y as Optional, y as default };