Can deep copy everything except invalid keys

pull/2/head
Louis Chatriot 10 years ago
parent 1bee5827bb
commit 0e26841681
  1. 10
      lib/model.js
  2. 16
      test/model.test.js

@ -99,8 +99,10 @@ function deserialize (rawData) {
/** /**
* Deep copy a DB object * Deep copy a DB object
* The optional strictKeys flag (defaulting to false) indicates whether to copy everything or only fields
* where the keys are valid, i.e. don't begin with $ and don't contain a .
*/ */
function deepCopy (obj) { function deepCopy (obj, strictKeys) {
var res; var res;
if ( typeof obj === 'boolean' || if ( typeof obj === 'boolean' ||
@ -113,14 +115,16 @@ function deepCopy (obj) {
if (util.isArray(obj)) { if (util.isArray(obj)) {
res = []; res = [];
obj.forEach(function (o) { res.push(deepCopy(o)); }); obj.forEach(function (o) { res.push(deepCopy(o, strictKeys)); });
return res; return res;
} }
if (typeof obj === 'object') { if (typeof obj === 'object') {
res = {}; res = {};
Object.keys(obj).forEach(function (k) { Object.keys(obj).forEach(function (k) {
res[k] = deepCopy(obj[k]); if (!strictKeys || (k[0] !== '$' && k.indexOf('.') === -1)) {
res[k] = deepCopy(obj[k], strictKeys);
}
}); });
return res; return res;
} }

@ -261,6 +261,22 @@ describe('Model', function () {
a[0].hello.should.equal('world'); a[0].hello.should.equal('world');
}); });
it('Without the strictKeys option, everything gets deep copied', function () {
var a = { a: 4, $e: 'rrr', 'eee.rt': 42, nested: { yes: 1, 'tt.yy': 2, $nopenope: 3 }, array: [{ 'rr.hh': 1 }, { yes: true }, { $yes: false }] }
, b = model.deepCopy(a)
;
assert.deepEqual(a, b);
});
it('With the strictKeys option, only valid keys gets deep copied', function () {
var a = { a: 4, $e: 'rrr', 'eee.rt': 42, nested: { yes: 1, 'tt.yy': 2, $nopenope: 3 }, array: [{ 'rr.hh': 1 }, { yes: true }, { $yes: false }] }
, b = model.deepCopy(a, true)
;
assert.deepEqual(b, { a: 4, nested: { yes: 1 }, array: [{}, { yes: true }, {}] });
});
}); // ==== End of 'Deep copying' ==== // }); // ==== End of 'Deep copying' ==== //

Loading…
Cancel
Save