observe
Version:
A powerful, pragmatic implementation of the observer pattern for javascript objects and arrays.
44 lines (35 loc) • 1.43 kB
JavaScript
// utilities needed by the configuration (excludes dependencies the configs don't need so the webpack bundle is lean)
var path = require('path')
// Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
// any number of objects can be passed into the function and will be merged into the first argument in order
// returns obj1 (now mutated)
var merge = exports.merge = function(obj1, obj2/*, moreObjects...*/){
return mergeInternal(arrayify(arguments), false)
}
// like merge, but traverses the whole object tree
// the result is undefined for objects with circular references
var deepMerge = exports.deepMerge = function(obj1, obj2/*, moreObjects...*/) {
return mergeInternal(arrayify(arguments), true)
}
function mergeInternal(objects, deep) {
var obj1 = objects[0]
var obj2 = objects[1]
for(var key in obj2){
if(Object.hasOwnProperty.call(obj2, key)) {
if(deep && obj1[key] instanceof Object && obj2[key] instanceof Object) {
mergeInternal([obj1[key], obj2[key]], true)
} else {
obj1[key] = obj2[key]
}
}
}
if(objects.length > 2) {
var newObjects = [obj1].concat(objects.slice(2))
return mergeInternal(newObjects, deep)
} else {
return obj1
}
}
function arrayify(a) {
return Array.prototype.slice.call(a, 0)
}