UNPKG

@mvst/ts-unions

Version:

TypeScript union types for Maybe and RemoteData with pattern matching

49 lines (48 loc) 1.69 kB
import { curry } from "./utils.js"; function notAsked() { return { type: "NotAsked" }; } function loading() { return { type: "Loading" }; } function success(value) { return { type: "Success", value }; } function error(error) { return { type: "Error", error }; } function isSuccess(remoteData) { return remoteData.type === "Success"; } function isError(remoteData) { return remoteData.type === "Error"; } function isLoading(remoteData) { return remoteData.type === "Loading"; } function isNotAsked(remoteData) { return remoteData.type === "NotAsked"; } const withDefault = curry(function withDefault(defaultValue, remoteData) { return isSuccess(remoteData) ? remoteData.value : defaultValue; }); const when = curry(function when(pattern, remoteData) { const { notAsked, loading, success, error, _ = Function.prototype } = pattern; switch (remoteData.type) { case "NotAsked": return typeof notAsked === "function" ? notAsked() : _(); case "Loading": return typeof loading === "function" ? loading() : _(); case "Success": return typeof success === "function" ? success(remoteData.value) : _(); case "Error": return typeof error === "function" ? error(remoteData.error) : _(); } }); const map = curry(function map(fn, remoteData) { return isSuccess(remoteData) ? success(fn(remoteData.value)) : remoteData; }); const andThen = curry(function andThen(fn, remoteData) { return isSuccess(remoteData) ? fn(remoteData.value) : remoteData; }); export { andThen, error, isError, isLoading, isNotAsked, isSuccess, loading, map, notAsked, success, when, withDefault, };