-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
81 lines (78 loc) · 1.82 KB
/
index.js
File metadata and controls
81 lines (78 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
var merge = require('lodash.merge')
var traverse = require('traverse')
/**
* Modify an object recursively by an array of sequential patches.
* @param {Object} input - Object input.
* @param {Array} patches - Array of patches.
* @returns {Object} Resulting object.
*/
module.exports = function (input, patches) {
if (typeof input !== 'object') {
throw new TypeError('Invalid first argument. Object is expected.')
}
if (!Array.isArray(patches)) {
throw new TypeError('Invalid second argument. Array is expected.')
}
return patches.reduce(apply, input)
}
function apply (source, patch) {
const tpatch = traverse(patch)
const tsource = traverse(source)
function transformNode (node) {
if (typeof node !== 'object' || Array.isArray(node)) {
return node
}
const path = this.path
return operations.reduce((result, operation) => {
if ({}.hasOwnProperty.call(node, operation.key)) {
return operation.run(node[operation.key], tsource.get(path))
}
return result
}, node)
}
return Object.assign({}, source, tpatch.map(transformNode))
}
var operations = [
{
key: '$set',
run: function (node, source) {
return node
}
},
{
key: '$push',
run: function (node, source) {
return source ? source.concat(node) : [node]
}
},
{
key: '$unshift',
run: function (node, source) {
return source ? [node].concat(source) : [node]
}
},
{
key: '$filter',
run: function (node, source) {
return source.filter(node)
}
},
{
key: '$map',
run: function (node, source) {
return source.map(node)
}
},
{
key: '$apply',
run: function (node, source) {
return node(source)
}
},
{
key: '$merge',
run: function (node, source) {
return merge({}, source, node)
}
}
]