Permalink
Browse files

Added `extend` and `defaults` util functions (with tests)

  • Loading branch information...
1 parent 3c06703 commit 8aeb9d782f0b7d6992c967287be8688b692986c9 @gilbert gilbert committed Feb 6, 2012
Showing with 77 additions and 0 deletions.
  1. +16 −0 lib/utils/misc.js
  2. +16 −0 src/utils/misc.js
  3. +45 −0 test/misc.coffee
View
@@ -15,3 +15,19 @@ exports.parseWsMessage = function (msg) {
throw new Error('Invalid message');
}
};
+
+// Taken from underscore.js
+exports.extend = function (obj) {
+ for (var i = 1; i < arguments.length; i++) {
+ var source = arguments[i];
+ for (var prop in source) {
+ obj[prop] = source[prop];
+ }
+ }
+ return obj;
+};
+
+// Useful for declaring default parameter
+exports.defaults = function (args, defaults) {
+ return exports.extend({}, defaults, args);
+};
View
@@ -15,3 +15,19 @@ exports.parseWsMessage = function (msg) {
throw new Error('Invalid message');
}
};
+
+// Taken from underscore.js
+exports.extend = function (obj) {
+ for (var i = 1; i < arguments.length; i++) {
+ var source = arguments[i];
+ for (var prop in source) {
+ obj[prop] = source[prop];
+ }
+ }
+ return obj;
+};
+
+// Useful for declaring default parameter
+exports.defaults = function (args, defaults) {
+ return exports.extend({}, defaults, args);
+};
View
@@ -0,0 +1,45 @@
+misc = require('../lib/utils/misc')
+
+describe 'Extend', ->
+
+ it 'should do nothing with a single argument', ->
+ one = a:1, b:2, c:3
+ misc.extend(one)
+ one.a.should.equal 1
+ one.b.should.equal 2
+ one.c.should.equal 3
+
+ it 'should merge two objects', ->
+ one = a:1, b:2, c:3
+ two = b:22
+ misc.extend(one, two)
+ one.b.should.equal 22
+
+ it 'should merge three objects', ->
+ one = a:1, b:2, c:3
+ two = b:22
+ three = c:33
+ misc.extend(one, two, three)
+ one.b.should.equal 22
+ one.c.should.equal 33
+
+ it 'should give priority to the last argument', ->
+ one = a:1, b:2, c:3
+ two = b:22, c:33
+ three = c:333
+ misc.extend(one, two, three)
+ one.b.should.equal 22
+ one.c.should.equal 333
+
+
+describe 'Defaults', ->
+
+ it 'should only be used for undeclared parameters', ->
+ args = a:1
+ newArgs = misc.defaults args,
+ a: 11
+ b: 22
+ c: 33
+ newArgs.a.should.equal 1
+ newArgs.b.should.equal 22
+ newArgs.c.should.equal 33

0 comments on commit 8aeb9d7

Please sign in to comment.