Skip to content

Commit 5b09e52

Browse files
committed
fix: handle number-type values inside keys array;
- ["foo", "10.0"] => object - ["foo", 10.0] => array ^ matches lodash - Closes #12
1 parent e6ef708 commit 5b09e52

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

index.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
export function dset<T extends object, V>(obj: T, keys: string | ArrayLike<string>, value: V): void;
1+
export function dset<T extends object, V>(obj: T, keys: string | ArrayLike<string | number>, value: V): void;

src/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@ export function dset(obj, keys, val) {
44
for (; i < l;) {
55
k = keys[i++];
66
if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
7-
t = t[k] = (i === l) ? val : (typeof(x=t[k])===typeof(keys)) ? x : (keys[i]*0 !== 0 || !!~keys[i].indexOf('.')) ? {} : [];
7+
t = t[k] = (i === l) ? val : (typeof(x=t[k])===typeof(keys)) ? x : (keys[i]*0 !== 0 || !!~(''+keys[i]).indexOf('.')) ? {} : [];
88
}
99
}

test/index.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,24 @@ keys('should add value to key path :: nested :: array', () => {
7171
});
7272
});
7373

74+
keys('should create Array via integer key :: string', () => {
75+
let input = {};
76+
dset(input, ['foo', '0'], 123);
77+
assert.instance(input.foo, Array);
78+
assert.equal(input, {
79+
foo: [123]
80+
})
81+
});
82+
83+
keys('should create Array via integer key :: number', () => {
84+
let input = {};
85+
dset(input, ['foo', 0], 123);
86+
assert.instance(input.foo, Array);
87+
assert.equal(input, {
88+
foo: [123]
89+
})
90+
});
91+
7492
keys.run();
7593

7694
// ---
@@ -117,7 +135,7 @@ arrays('should create arrays with hole(s) if needed', () => {
117135
});
118136
});
119137

120-
arrays('should create object from decimal-like key :: array :: zero', () => {
138+
arrays('should create object from decimal-like key :: array :: zero :: string', () => {
121139
let input = {};
122140
dset(input, ['x', '10.0', 'z'], 123);
123141
assert.not.instance(input.x, Array);
@@ -130,6 +148,16 @@ arrays('should create object from decimal-like key :: array :: zero', () => {
130148
});
131149
});
132150

151+
arrays('should create array from decimal-like key :: array :: zero :: number', () => {
152+
let input = {};
153+
dset(input, ['x', 10.0, 'z'], 123);
154+
assert.instance(input.x, Array);
155+
156+
let x = Array(10);
157+
x.push({ z: 123 });
158+
assert.equal(input, { x });
159+
});
160+
133161
arrays('should create object from decimal-like key :: array :: nonzero', () => {
134162
let input = {};
135163
dset(input, ['x', '10.2', 'z'], 123);

0 commit comments

Comments
 (0)