import map from 'lodash/map' import flatMap from 'lodash/flatMap' export function maybe(defaultValue: () => O, f: (v: I) => O, v?: I | null): O { return v === undefined || v === null ? defaultValue() : f(v) } export function fromJust(a: A | undefined | null, error: string): A { if (a === undefined || a === null) { throw new Error(error) } else { return a } } export function fromMaybe(defaultValue: () => T, t?: T | null): T { return t === null || t === undefined ? defaultValue() : t } export const catMaybes = (array: Array): Array => flatMap(array, x => (x === null || x === undefined ? [] : [x])) export function mapMaybes( array: Array, callback: (value: A, index: number, array: ReadonlyArray) => B | undefined | null ): Array { return catMaybes(map(array, callback)) } // fmap for `null | undefined` export const mmap = (f: (v: I) => O, v?: I | null): O | undefined | null => v === undefined ? undefined : v === null ? null : f(v) // bind for `null | undefined` // Note that `bind` and `map` have the same body in JavaScript export const mthen = ( v: I | undefined | null, f: (v: I) => O | undefined | null ): O | undefined | null => (v === undefined ? undefined : v === null ? null : f(v)) // mthen for effects (and not transformations, hence nothing is returned) export function mEffect(v: V | undefined | null, effect: (v: V) => void) { if (v !== null && v !== undefined) { effect(v) } } // create an object with the given property/value, when the value is present export const mObj =

(p: P, v?: V | null): Partial> => v === null || v === undefined ? {} : ({[p]: v} as Record) /* asHTMLAttributeValue is used as a way to make an HTML attribute value * exist in the DOM or not. React does not add in the DOM HTML attributes * with an "undefined" value * eg. * * const disabled = null * const disabledObj = {disabled: asHTMLAttributeValue(disabled)} *