UNPKG

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