From b581078a020e951c55d2e554221c5248e1b59875 Mon Sep 17 00:00:00 2001 From: Grzegorz Osimowicz Date: Tue, 1 Jun 2021 12:50:38 +0200 Subject: [PATCH 1/2] Use spread operator instead of for in Merge should not mutate input parameter Fixes https://github.com/jaredhanson/utils-merge/issues/8#issue-880654538 --- index.js | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index 4265c69..9b0fe6c 100644 --- a/index.js +++ b/index.js @@ -14,10 +14,8 @@ */ exports = module.exports = function(a, b){ - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; + return { + ...(a ?? {}), + ...(b ?? {}) + }; }; From 9a43929d54d063719cc01c33de24d87420476f48 Mon Sep 17 00:00:00 2001 From: Grzegorz Osimowicz Date: Tue, 1 Jun 2021 13:20:23 +0200 Subject: [PATCH 2/2] Added tests for mutating objects --- test/index.test.js | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/test/index.test.js b/test/index.test.js index 7241855..0202d3b 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -47,5 +47,23 @@ describe('merge', function() { expect(o).to.be.equal(a); }); }); - + + it('should not mutate first parameter', function() { + const foo = { foo: "foo" }; + const bar = { bar: "bar" }; + const result = merge(foo, bar); + expect(Object.keys(foo)).to.have.length(1); + expect(result.foo).to.be.equal('foo'); + expect(result.bar).to.be.equal('bar'); + }); + + + it('should not mutate second parameter', function() { + const foo = { foo: "foo" }; + const bar = { bar: "bar" }; + const result = merge(foo, bar); + expect(Object.keys(bar)).to.have.length(1); + expect(result.foo).to.be.equal('foo'); + expect(result.bar).to.be.equal('bar'); + }); });