Skip to content

Commit

Permalink
Close GH-862: Add util namespace.
Browse files Browse the repository at this point in the history
  • Loading branch information
heff committed Dec 3, 2013
1 parent 09f81c0 commit 2aa09fd
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 1 deletion.
1 change: 1 addition & 0 deletions build/source-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ var sourceFiles = [
"src/js/core-object.js",
"src/js/events.js",
"src/js/lib.js",
"src/js/util.js",
"src/js/component.js",
"src/js/button.js",
"src/js/slider.js",
Expand Down
2 changes: 1 addition & 1 deletion src/js/component.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ vjs.Component.prototype.options_;
vjs.Component.prototype.options = function(obj){
if (obj === undefined) return this.options_;

return this.options_ = vjs.obj.deepMerge(this.options_, obj);
return this.options_ = vjs.util.mergeOptions(this.options_, obj);
};

/**
Expand Down
40 changes: 40 additions & 0 deletions src/js/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Utility functions namespace
* @namespace
* @type {Object}
*/
vjs.util = {};

/**
* Merge two options objects,
* recursively merging any plain object properties as well.
* Previously `deepMerge`
*
* @param {Object} obj1 Object to override values in
* @param {Object} obj2 Overriding object
* @return {Object} New object -- obj1 and obj2 will be untouched
*/
vjs.util.mergeOptions = function(obj1, obj2){
var key, val1, val2;

// make a copy of obj1 so we're not ovewriting original values.
// like prototype.options_ and all sub options objects
obj1 = vjs.obj.copy(obj1);

for (key in obj2){
if (obj2.hasOwnProperty(key)) {
val1 = obj1[key];
val2 = obj2[key];

// Check if both properties are pure objects and do a deep merge if so
if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) {
obj1[key] = vjs.util.mergeOptions(val1, val2);
} else {
obj1[key] = obj2[key];
}
}
}
return obj1;
};


29 changes: 29 additions & 0 deletions test/unit/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module('util');

test('should merge options objects', function(){
var ob1, ob2, ob3;

ob1 = {
a: true,
b: { b1: true, b2: true, b3: true },
c: true
};

ob2 = {
// override value
a: false,
// merge sub-option values
b: { b1: true, b2: false, b4: true },
// add new option
d: true
};

ob3 = vjs.util.mergeOptions(ob1, ob2);

deepEqual(ob3, {
a: false,
b: { b1: true, b2: false, b3: true, b4: true },
c: true,
d: true
}, 'options objects merged correctly');
});

0 comments on commit 2aa09fd

Please sign in to comment.