aboutsummaryrefslogtreecommitdiffstats
path: root/sdv/pdf/site/scripts/mergeDeep.js
diff options
context:
space:
mode:
Diffstat (limited to 'sdv/pdf/site/scripts/mergeDeep.js')
-rw-r--r--sdv/pdf/site/scripts/mergeDeep.js31
1 files changed, 31 insertions, 0 deletions
diff --git a/sdv/pdf/site/scripts/mergeDeep.js b/sdv/pdf/site/scripts/mergeDeep.js
new file mode 100644
index 0000000..ebede4e
--- /dev/null
+++ b/sdv/pdf/site/scripts/mergeDeep.js
@@ -0,0 +1,31 @@
+
+/**
+* Performs a deep merge of objects and returns new object. Does not modify
+* objects (immutable) and merges arrays via concatenation.
+*
+* @param {...object} objects - Objects to merge
+* @returns {object} New object with merged key/values
+*/
+function mergeDeep(...objects) {
+ const isObject = obj => obj && typeof obj === 'object';
+
+ return objects.reduce((prev, obj) => {
+ Object.keys(obj).forEach(key => {
+ const pVal = prev[key];
+ const oVal = obj[key];
+
+ if (Array.isArray(pVal) && Array.isArray(oVal)) {
+ prev[key] = pVal.concat(...oVal);
+ }
+ else if (isObject(pVal) && isObject(oVal)) {
+ prev[key] = mergeDeep(pVal, oVal);
+ }
+ else {
+ prev[key] = oVal;
+ }
+ });
+
+ return prev;
+ }, {});
+}
+