Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add deepKeys() #94

Merged
merged 8 commits into from Feb 17, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 28 additions & 4 deletions index.js
Expand Up @@ -285,17 +285,41 @@ export function escapePath(path) {
return path.replace(/[\\.[]/g, '\\$&');
}

// The keys returned by Object.entries() for arrays are strings
function entries(value) {
if (Array.isArray(value)) {
return value.map((value, index) => [index, value]);
Richienb marked this conversation as resolved.
Show resolved Hide resolved
}

return Object.entries(value);
}

function stringifyPath(pathSegments) {
let result = '';

for (let [index, segment] of entries(pathSegments)) {
if (typeof segment === 'number') {
result += `[${segment}]`;
Richienb marked this conversation as resolved.
Show resolved Hide resolved
} else {
segment = escapePath(segment);
result += index === 0 ? segment : `.${segment}`;
}
}

return result;
}

function * deepKeysIterator(object, currentPath = []) {
if (!isObject(object) || Array.isArray(object)) {
if (!isObject(object)) {
if (currentPath.length > 0) {
yield currentPath.join('.');
yield stringifyPath(currentPath);
}

return;
}

for (const [key, value] of Object.entries(object)) {
yield * deepKeysIterator(value, [...currentPath, escapePath(key)]);
for (const [key, value] of entries(object)) {
yield * deepKeysIterator(value, [...currentPath, key]);
}
}

Expand Down
8 changes: 7 additions & 1 deletion test.js
Expand Up @@ -419,11 +419,17 @@ test('deepKeys', t => {
a: 0,
},
},
'': {
a: 0,
},
}), [
'a\\.b.c.d',
'a\\.b.c.d[0]',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you want to be extra thorough you could cover the case where an array contains a complex object too, but I imagine it’s fine.

'a\\.b.c.d[1]',
'a\\.b.c.d[2]',
'a\\.b.c.e',
'a\\.b.c.f',
'a\\.b..a',
'.a',
]);
Richienb marked this conversation as resolved.
Show resolved Hide resolved

t.deepEqual(deepKeys([]), []);
Expand Down