Skip to content

Commit

Permalink
Fix deepKeys to not throw on sparse arrays
Browse files Browse the repository at this point in the history
Fixes #108
  • Loading branch information
sindresorhus committed Jun 29, 2023
1 parent bf6224b commit f21b68e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,8 @@ export function escapePath(path) {
// The keys returned by Object.entries() for arrays are strings
function entries(value) {
if (Array.isArray(value)) {
return value.map((value, index) => [index, value]);
// We use `[...value]` to convert sparse entries to normal ones.
return [...value].map((value, index) => [index, value]);
}

return Object.entries(value);
Expand Down
15 changes: 15 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,7 @@ test('deepKeys', t => {
a: 0,
},
};

const keys = deepKeys(object);

t.deepEqual(keys, [
Expand Down Expand Up @@ -463,6 +464,20 @@ test('deepKeys', t => {
t.deepEqual(deepKeys(0), []);
});

test('deepKeys - does not throw on sparse array', t => {
const object = {
sparse: [1,,3], // eslint-disable-line no-sparse-arrays, comma-spacing
};

const keys = deepKeys(object);

t.deepEqual(keys, [
'sparse[0]',
'sparse[1]',
'sparse[2]',
]);
});

test('prevent setting/getting `__proto__`', t => {
setProperty({}, '__proto__.unicorn', '🦄');
t.not({}.unicorn, '🦄'); // eslint-disable-line no-use-extend-native/no-use-extend-native
Expand Down

0 comments on commit f21b68e

Please sign in to comment.