From 049d4c9ba4da1deecdfcef716b56b826b1daaf87 Mon Sep 17 00:00:00 2001 From: Kit Cambridge Date: Tue, 9 Jul 2013 01:47:54 -0700 Subject: [PATCH] Optimize `Model#update` and ensure that it ignores primitive argument values. --- lib/polyclay.js | 17 +++++++---------- test/test-01-polyclay.js | 36 ++++++++++++++++++++++++------------ 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/lib/polyclay.js b/lib/polyclay.js index c0969d3..2299db8 100644 --- a/lib/polyclay.js +++ b/lib/polyclay.js @@ -354,18 +354,15 @@ PolyClay.Model.prototype.propertyTypes = function() PolyClay.Model.prototype.update = function(attr) { - var k, - self = this, - props = Object.keys(attr), - whitelist = _.union(this.__optional, this.__properties) - ; - for (var i = 0; i < props.length; i++) + if (!_.isObject(attr)) + return; + + var whitelist = _.union(this.__optional, this.__properties); + for (var i = 0; i < whitelist.length; i++) { - k = props[i]; - if ((whitelist.indexOf(k) !== -1) && (k !== undefined)) + var k = whitelist[i]; + if (_.has(attr, k)) this[k] = attr[k]; - //else - // console.log('skipping unknown property ' + k); } this.trigger('update'); }; diff --git a/test/test-01-polyclay.js b/test/test-01-polyclay.js index 73abcdc..f5aa073 100644 --- a/test/test-01-polyclay.js +++ b/test/test-01-polyclay.js @@ -491,20 +491,32 @@ describe('polyclay', function() struct.should.have.property(checklist[i]); }); - it('updates all known properties in update()', function() + describe('#update', function() { - var data = { - is_valid: true, - foozles: ['three', 'four'], - count: 50, - required_prop: 'badges' - }; - var obj = new Model(); - obj.update(data); + it('updates all known properties', function() + { + var data = { + is_valid: true, + foozles: ['three', 'four'], + count: 50, + required_prop: 'badges' + }; + var obj = new Model(); + obj.update(data); + + obj.required_prop.should.equal(data.required_prop); + obj.count.should.equal(data.count); + obj.is_valid.should.equal(data.is_valid); + }); - obj.required_prop.should.equal(data.required_prop); - obj.count.should.equal(data.count); - obj.is_valid.should.equal(data.is_valid); + it('ignores primitive argument values', function() + { + var obj = new Model(); + should.not.throw(function() { obj.update(); }); + should.not.throw(function() { obj.update(null); }); + should.not.throw(function() { obj.update('snozzers'); }); + should.not.throw(function() { obj.update(false); }); + }); }); it('emits a "change" event when a property is set', function(done)