UNPKG

1.95 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
3 typeof define === 'function' && define.amd ? define(factory) :
4 (factory());
5}(this, (function () { 'use strict';
6
7var Op = require('object-path');
8var Traverse = require('traverse');
9
10module.exports = function (mapDefinition, defaults) {
11
12 defaults = defaults || {};
13
14 return function (originalObj) {
15 return Traverse(mapDefinition).map(
16 /*eslint-disable prefer-arrow-callback */
17 function (item) {
18
19 var getMethod = 'get';
20 var path = item;
21 var process = function process(x) {
22 return x;
23 };
24
25 if (!this.isLeaf) {
26 var isObject = Object.prototype.toString.apply(item) === '[object Object]';
27 var hasAlternatives = isObject && Array.isArray(item.alternatives);
28 var hasProcessor = isObject && typeof item.processor === 'function';
29 // not leaf, not alternatives, no processor, this means a regular object so skip
30 // it
31 if (!hasAlternatives && !hasProcessor) {
32 return;
33 }
34 if (hasAlternatives) {
35 path = item.alternatives;
36 getMethod = 'coalesce';
37 }
38 if (hasProcessor) {
39 if (!hasAlternatives && !item.path) {
40 console.warn('You have provided a processor func. without path or alternatives. Null will be returned');
41 return null;
42 }
43 path = hasAlternatives ? path : item.path;
44 process = item.processor;
45 }
46 }
47
48 var originalValue = Op[getMethod](originalObj, path);
49 // try to use a default value ONLY if the original value is undefined. Values like false, 0, '', null, will pass as they are
50 originalValue = originalValue === undefined ? Op[getMethod](defaults, path) : originalValue;
51
52 var newValue = process(originalValue, originalObj);
53
54 this.update(newValue, true);
55 });
56 };
57};
58
59})));