1 | 'use strict';
|
2 | const Op = require(`object-path`);
|
3 | const Traverse = require(`traverse`);
|
4 |
|
5 | module.exports = (mapDefinition, defaults) => {
|
6 |
|
7 | defaults = defaults || {};
|
8 |
|
9 | return originalObj => Traverse(mapDefinition).map(
|
10 |
|
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 |
|
22 |
|
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 |
|
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 | };
|