Skip to content

Commit

Permalink
Fix crashing modifying array length
Browse files Browse the repository at this point in the history
Also avoids unnecessary allocation and set.

Fixes cases like the following:
```javascript
let obj = { a: [1,2] };
dotProp.delete(obj, 'a.1');
dotProp.set(obj, 'a.length', 1);
```
Previously would throw `Uncaught RangeError: Invalid array length` when it tries to set `obj.a.length = {}`
  • Loading branch information
Jimbly committed Jan 22, 2022
1 parent 0289e19 commit 7ca5c6a
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
6 changes: 2 additions & 4 deletions index.js
Expand Up @@ -219,12 +219,10 @@ export function setProperty(object, path, value) {

assertNotStringIndex(object, key);

if (!isObject(object[key])) {
object[key] = typeof pathArray[index + 1] === 'number' ? [] : {};
}

if (index === pathArray.length - 1) {
object[key] = value;
} else if (!isObject(object[key])) {
object[key] = typeof pathArray[index + 1] === 'number' ? [] : {};
}

object = object[key];
Expand Down
5 changes: 5 additions & 0 deletions test.js
Expand Up @@ -245,6 +245,11 @@ test('setProperty', t => {
bar: true,
}],
});

const fixture7 = {foo: ['bar', 'baz']};
setProperty(fixture7, 'foo.length', 1);
t.is(fixture7.foo.length, 1);
t.deepEqual(fixture7, {foo: ['bar']});
});

test('deleteProperty', t => {
Expand Down

0 comments on commit 7ca5c6a

Please sign in to comment.