Skip to content

Commit ecdd912

Browse files
committed
refactor: extract deepMerge function
1 parent 2813655 commit ecdd912

File tree

2 files changed

+27
-24
lines changed

2 files changed

+27
-24
lines changed

deepMerge.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const isObject = val => val && typeof val === 'object'
2+
const mergeArrayWithDedupe = (a, b) => Array.from(new Set([...a, ...b]))
3+
4+
/**
5+
* Recursively merge the content of the new object to the existing one
6+
* @param {Object} target the existing object
7+
* @param {Object} obj the new object
8+
*/
9+
function deepMerge(target, obj) {
10+
for (const key of Object.keys(obj)) {
11+
const oldVal = target[key]
12+
const newVal = obj[key]
13+
14+
if (Array.isArray(oldVal) && Array.isArray(newVal)) {
15+
target[key] = mergeArrayWithDedupe(oldVal, newVal)
16+
} else if (isObject(oldVal) && isObject(newVal)) {
17+
target[key] = deepMerge(oldVal, newVal)
18+
} else {
19+
target[key] = newVal
20+
}
21+
}
22+
23+
return target
24+
}
25+
26+
export default deepMerge

renderTemplate.js

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,7 @@
11
import fs from 'fs'
22
import path from 'path'
33

4-
const isObject = val => val && typeof val === 'object'
5-
const mergeArrayWithDedupe = (a, b) => Array.from(new Set([...a, ...b]))
6-
7-
/**
8-
* Recursively merge the content of the new object to the existing one
9-
* @param {Object} target the existing object
10-
* @param {Object} obj the new object
11-
*/
12-
function deepMerge(target, obj) {
13-
for (const key of Object.keys(obj)) {
14-
const oldVal = target[key]
15-
const newVal = obj[key]
16-
17-
if (Array.isArray(oldVal) && Array.isArray(newVal)) {
18-
target[key] = mergeArrayWithDedupe(oldVal, newVal)
19-
} else if (isObject(oldVal) && isObject(newVal)) {
20-
target[key] = deepMerge(oldVal, newVal)
21-
} else {
22-
target[key] = newVal
23-
}
24-
}
25-
26-
return target
27-
}
4+
import deepMerge from './deepMerge.js'
285

296
/**
307
* Renders a template folder/file to the file system,

0 commit comments

Comments
 (0)