UNPKG

object-translate

Version:
77 lines (65 loc) 2.93 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory() : typeof define === 'function' && define.amd ? define(factory) : (factory()); }(this, (function () { 'use strict'; 'use strict'; var Op = require('object-path'); var Traverse = require('traverse'); var tryDefault = function tryDefault(method, src, path, altPath) { var def = Op[method](src, path); return def === undefined ? Op[method](src, altPath) : def; }; /** * @function {function name} * @param {Object} mapDefinition Mapping description describing the final shape you want and paths to where those values are * @param {Object} defaults An object with default values on the same paths as the expected object * @param {Object} options An object containing additional options * @param {String = $default} Options.defaultPath Name of the default path when something does not exist on the defaults object * @return {Function} A converter function with the provided configuration */ module.exports = function (mapDefinition, defaults) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$defaultPath = _ref.defaultPath, defaultPath = _ref$defaultPath === undefined ? '$default' : _ref$defaultPath; defaults = defaults || {}; return function (originalObj) { return Traverse(mapDefinition).map( /*eslint-disable prefer-arrow-callback */ function (item) { var getMethod = 'get'; var path = item; var process = function process(x) { return x; }; if (!this.isLeaf) { var isObject = Object.prototype.toString.apply(item) === '[object Object]'; var hasAlternatives = isObject && Array.isArray(item.alternatives); var hasProcessor = isObject && typeof item.processor === 'function'; // not leaf, not alternatives, no processor, this means a regular object so skip // it to traverse it later if (!hasAlternatives && !hasProcessor) { return; } if (hasAlternatives) { path = item.alternatives; getMethod = 'coalesce'; } if (hasProcessor) { if (!hasAlternatives && !item.path) { console.warn('You have provided a processor func. without path or alternatives. Null will be returned'); return null; } path = hasAlternatives ? path : item.path; process = item.processor; } } var originalValue = Op[getMethod](originalObj, path); // try to use a default value ONLY if the original value is undefined. Values like false, 0, '', null, will pass as they are originalValue = originalValue === undefined ? tryDefault(getMethod, defaults, path, defaultPath) : originalValue; var newValue = process(originalValue, originalObj); this.update(newValue, true); }); }; }; })));