UNPKG

map-transform

Version:

Map and transform objects with mapping definitions

48 lines 1.84 kB
import mapAny from 'map-any'; import { escapeValue, unescapeValue } from '../utils/escape.js'; import xor from '../utils/xor.js'; const isSupportedValue = (data) => ['string', 'number', 'boolean'].includes(typeof data) || data === null || data === undefined; function findFirstMatch(value, dictionary, direction) { const match = dictionary.find((dict) => dict[direction] === value); return match ? match[1 - direction] : undefined; } function translate(data, dictionary, rev) { const direction = Number(rev); return mapAny((data) => { const value = isSupportedValue(data) ? data : undefined; const match = findFirstMatch(value, dictionary, direction); if (match === undefined || match === '*') { const starMatch = findFirstMatch('*', dictionary, direction); return starMatch === undefined ? match : starMatch; } return match; }, data); } function extractDictionary(dictionary, dictionaries) { if (typeof dictionary === 'string') { return dictionaries && dictionaries[dictionary]; } else { return dictionary; } } const escapeDictionary = (dictionary) => dictionary ? dictionary.map(([from, to]) => [escapeValue(from), escapeValue(to)]) : undefined; const transformer = function map(props) { return (options) => { const dictionary = escapeDictionary(extractDictionary(props.dictionary, options && options.dictionaries)); if (!dictionary) { return () => undefined; } return (data, state) => { const rev = xor(state.rev, props.flip); const match = translate(escapeValue(data), dictionary, rev); return match === '*' ? data : unescapeValue(match); }; }; }; export default transformer; //# sourceMappingURL=map.js.map