Skip to content

Commit

Permalink
Merge pull request #468 from BrendanAnnable/copy-descriptors
Browse files Browse the repository at this point in the history
Add support for non-enumerable properties
  • Loading branch information
Yomguithereal authored Jan 19, 2017
2 parents 3266b02 + 5d873ae commit 8d532f8
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -206,19 +206,26 @@ function cloner(deep, item) {
if (type.object(item)) {
const o = {};

let k;
let i, l, k;

// NOTE: could be possible to erase computed properties through `null`.
for (k in item) {
const props = Object.getOwnPropertyNames(item);
for (i = 0, l = props.length; i < l; i++) {
k = props[i];
if (type.lazyGetter(item, k)) {
Object.defineProperty(o, k, {
get: Object.getOwnPropertyDescriptor(item, k).get,
enumerable: true,
configurable: true
});
}
else if (hasOwnProp.call(item, k)) {
o[k] = deep ? cloner(true, item[k]) : item[k];
else {
Object.defineProperty(o, k, {
value: deep ? cloner(true, item[k]) : item[k],
enumerable: Object.getOwnPropertyDescriptor(item, k).enumerable,
writable: true,
configurable: true
});
}
}
return o;
Expand Down
39 changes: 39 additions & 0 deletions test/suites/cursor.js
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,45 @@ describe('Cursor API', function() {
}, /solve/);
});

it('should support setting non-enumerable properties', function() {
const tree = new Baobab(Object.create({}, {
id: {value: 2, writable: true, enumerable: true},
hello: {value: 'world', writable: true, enumerable: false}
})),
cursor = tree.select('hello');

cursor.set('universe');
assert.equal(cursor.get(), 'universe');
assert.equal(Object.getOwnPropertyDescriptor(tree.get(), 'id').enumerable, true);
assert.equal(Object.getOwnPropertyDescriptor(tree.get(), 'hello').enumerable, false);
});

it('should support setting deep non-enumerable properties', function() {
const tree = new Baobab(Object.create({}, {
id: {
value: 2,
writable: true,
enumerable: true
},
one: {
value: Object.create({}, {two: {
value: 'three',
writable: true,
enumerable: false
}}),
writable: true,
enumerable: false,
}
})),
cursor = tree.select(['one', 'two']);

cursor.set('four');
assert.equal(tree.get(['one', 'two']), 'four');
assert.equal(Object.getOwnPropertyDescriptor(tree.get(), 'id').enumerable, true);
assert.equal(Object.getOwnPropertyDescriptor(tree.get(), 'one').enumerable, false);
assert.equal(Object.getOwnPropertyDescriptor(tree.get('one'), 'two').enumerable, false);
});

it('should be possible to shallow merge two objects.', function(done) {
const tree = new Baobab({o: {hello: 'world'}, string: 'test'});

Expand Down

0 comments on commit 8d532f8

Please sign in to comment.