From 4ca581e0d898870436280c984b67af1e7102a824 Mon Sep 17 00:00:00 2001 From: Alex Kostyukov Date: Fri, 3 Mar 2023 20:49:54 +0300 Subject: [PATCH] fix deepkeys to work with empty arrays and objects --- index.js | 4 +++- test.js | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index c4abc95..e699982 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,8 @@ const isObject = value => { return value !== null && (type === 'object' || type === 'function'); }; +const isEmptyObject = value => isObject(value) && Object.keys(value).length === 0; + const disallowedKeys = new Set([ '__proto__', 'prototype', @@ -316,7 +318,7 @@ function stringifyPath(pathSegments) { } function * deepKeysIterator(object, currentPath = []) { - if (!isObject(object)) { + if (!isObject(object) || isEmptyObject(object)) { if (currentPath.length > 0) { yield stringifyPath(currentPath); } diff --git a/test.js b/test.js index 556d810..712ff0d 100644 --- a/test.js +++ b/test.js @@ -413,6 +413,8 @@ test('escapePath', t => { test('deepKeys', t => { const object = { + x: {}, + y: [], 'a.b': { c: { d: [1, 2, { @@ -420,6 +422,11 @@ test('deepKeys', t => { }], e: '🦄', f: 0, + h: {}, + i: [], + nu: null, + na: Number.NaN, + un: undefined, }, '': { a: 0, @@ -432,11 +439,18 @@ test('deepKeys', t => { const keys = deepKeys(object); t.deepEqual(keys, [ + 'x', + 'y', 'a\\.b.c.d[0]', 'a\\.b.c.d[1]', 'a\\.b.c.d[2].g', 'a\\.b.c.e', 'a\\.b.c.f', + 'a\\.b.c.h', + 'a\\.b.c.i', + 'a\\.b.c.nu', + 'a\\.b.c.na', + 'a\\.b.c.un', 'a\\.b..a', '.a', ]);