Skip to content

Commit

Permalink
feat(clone) Check for & use cloneOf method when cloning objects
Browse files Browse the repository at this point in the history
Adds a check in the `clone` function to see if the given parameter has
a `cloneOf` method.  If the method exists then the `clone` method
assumes that this method will return a clone of the called object and
thus invokes it to complete its task.

Fixes Automattic#8299
  • Loading branch information
stieg committed Nov 6, 2019
1 parent de3eee5 commit 8060e7e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/utils.js
Expand Up @@ -199,6 +199,10 @@ exports.clone = function clone(obj, options, isArrayChild) {
return obj.toObject(options);
}

if (typeof obj.cloneOf === 'function') {
return obj.cloneOf();
}

if (obj.constructor) {
switch (exports.getFunctionName(obj.constructor)) {
case 'Object':
Expand Down
16 changes: 16 additions & 0 deletions test/utils.test.js
Expand Up @@ -254,6 +254,22 @@ describe('utils', function() {

return Promise.resolve();
});

it('invokes cloneOf method on object before valueOf if exists', function(done) {
const o = Object.create({
cloneOf() {
this.cloneOfCalled = true;
return this;
},
});

const out = utils.clone(o);
assert.deepEqual(out, o);
assert.equal(o.cloneOfCalled, true);
assert.equal(out.valueOfCalled, undefined);

done();
});
});

it('array.flatten', function(done) {
Expand Down

0 comments on commit 8060e7e

Please sign in to comment.