UNPKG

voided-data

Version:

Proper DS for TS

64 lines (53 loc) 1.64 kB
"use strict"; /* Motivation: Let's imagine a data structure like a map with such an interface Map<K,V> { set(k: K, v: V) => void get(k: K) => V } When we want to get some data out of the Map we can't be sure if the key we used actually existed. What do we return from the Map in such a case and remain type safe? Null? Undefined? Throw an error? We don't want to throw an error, that's just annoying! Also, there is no typesafe way to make sure we handle that thrown error. What about null or undefined? Map<K,V> { set(k: K, v: V) => void get(k: K) => V | undefined } const value = Map<string, number>.get("some key") if (value === undefined) handle the missing key But what if our value is a union with undefined? const value Map<string, number | undefined>.get("some key") if (value === undefined) ... what does that mean? Is the key missing? Is the value undefined? Maybe<T> = Some<T> | None<T> */ Object.defineProperty(exports, "__esModule", { value: true }); exports.none = exports.some = exports.isNone = exports.isSome = void 0; function isSome(maybe) { return 'just' in maybe; } exports.isSome = isSome; function isNone(maybe) { return !isSome(maybe); } exports.isNone = isNone; function some(just) { return { just, map: (m) => some(m(just)), // eslint-disable-next-line @typescript-eslint/no-unused-vars match: (onSome, _) => onSome(just), }; } exports.some = some; function none() { return { map: () => none(), match: (_, onNone) => onNone(), }; } exports.none = none;