map-fn
v0.1.0
Published
A set of utility functions to map one type of values to another one with ease.
Downloads
76
Readme
map-fn
A set of utility functions to map one type of values to another one with ease.
Installation
pnpm add map-fn -P
Usage
import { createMapFn } from 'map-fn';
type A = 'foo' | 'bar' | 'baz';
type B = 'FOO' | 'BAR' | 'BAZ';
const mapAB = createMapFn<A, B>({
foo: 'FOO',
bar: 'BAR'
});
console.log(mapAB('foo')); // 'FOO'
console.log(mapAB('bar')); // 'BAR'
If no corresponding value is provided then MappingError
will be thrown:
console.log(mapAB('baz')); // MappingError
There are three options to avoid MappingError
in such cases:
Provide default value in
createMapFn
:const mapAB = createMapFn<A, B>({ foo: 'FOO', bar: 'BAR' }, { defaultValue: 'BAZ' }); console.log(mapAB('baz')); // 'BAZ'
Provide default value calling mapping function:
const mapAB = createMapFn<A, B>({ foo: 'FOO', bar: 'BAR' }); console.log(mapAB('baz', { defaultValue: 'BAZ' })); // 'BAZ'
Use
createMapFnUndefined
instead. Please note that output type will beB | undefined
(notB
):const mapAB = createMapFnUndefined<A, B>({ foo: 'FOO', bar: 'BAR' }); console.log(mapAB('baz')); // undefined