Skip to content

Commit

Permalink
break: overwrite existing non-object values if needed
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeed committed Jan 28, 2021
1 parent 113244b commit 569955d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 29 deletions.
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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('.')) ? {} : [];
}
}
48 changes: 20 additions & 28 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand All @@ -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();

// ---
Expand Down Expand Up @@ -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', () => {
Expand Down

0 comments on commit 569955d

Please sign in to comment.