From 569955dd94a5157047f5bceabf2500d20c1dee35 Mon Sep 17 00:00:00 2001 From: Luke Edwards Date: Wed, 27 Jan 2021 12:02:00 -0800 Subject: [PATCH] break: overwrite existing non-object values if needed --- src/index.js | 2 +- test/index.js | 48 ++++++++++++++++++++---------------------------- 2 files changed, 21 insertions(+), 29 deletions(-) diff --git a/src/index.js b/src/index.js index 0582cee..d33723d 100644 --- a/src/index.js +++ b/src/index.js @@ -4,6 +4,6 @@ export default function (obj, keys, val) { for (; i < l;) { k = keys[i++]; if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue; - t = t[k] = (i === l ? val : ((x=t[k]) != null ? x : (keys[i]*0 !== 0 || !!~keys[i].indexOf('.')) ? {} : [])); + t = t[k] = (i === l) ? val : (typeof(x=t[k])===typeof(keys)) ? x : (keys[i]*0 !== 0 || !!~keys[i].indexOf('.')) ? {} : []; } } diff --git a/test/index.js b/test/index.js index 2fab553..7f93abc 100644 --- a/test/index.js +++ b/test/index.js @@ -172,20 +172,22 @@ preserves('should preserve existing object structure', () => { }); }); -preserves('should not convert existing non-object values into object', () => { +preserves('should overwrite existing non-object values as object', () => { let input = { a: { b: 123 } }; - let before = JSON.stringify(input); dset(input, 'a.b.c', 'hello'); - assert.is( - JSON.stringify(input), - before - ); + assert.equal(input, { + a: { + b: { + c: 'hello' + } + } + }); }); preserves('should preserve existing object tree w/ array value', () => { @@ -208,26 +210,6 @@ preserves('should preserve existing object tree w/ array value', () => { }); }); -preserves('should not throw when refusing to convert non-object into object', () => { - try { - let input = { b:123 }; - dset(input, 'b.c.d.e', 123); - assert.is(input.b, 123); - } catch (err) { - assert.unreachable('should not have thrown'); - } -}); - -preserves('should not throw when refusing to convert `0` into object', () => { - try { - let input = { b:0 }; - dset(input, 'b.a.s.d', 123); - assert.equal(input, { b: 0 }); - } catch (err) { - assert.unreachable('should not have thrown'); - } -}); - preserves.run(); // --- @@ -274,8 +256,18 @@ pollution('should ignore "prototype" assignment', () => { dset(input, 'a.prototype.hello', 'world'); assert.is(input.a.prototype, undefined); - assert.is.not(input.a.hello, 'world'); - assert.equal(input, { a: 123 }); + assert.is(input.a.hello, 'world'); + + assert.equal(input, { + a: { + hello: 'world' + } + }); + + assert.is( + JSON.stringify(input), + '{"a":{"hello":"world"}}' + ); }); pollution('should ignore "constructor" assignment', () => {