Some issues?
typeof
is not a function. eg typeof(input) === 'object'
is written typeof input === 'object'
null
is an Object
so when you test for an object using typeof
you MUST make sure it is not null
as well.
The test that you comment as // catch null or undefined object
will catch any value that evaluates to a falsey, such as false
, 0
, ""
What is empty?
As it is unclear what you define as empty so I will make some assumptions, they are arbitrary and may or may not fit your needs.
- An array is empty if it contains only empty items.
- An object is empty if it is
null
or contains no own properties. If it has properties that are null
or (defined as) undefined
it is not empty.
- A string is empty if it contains no characters
- Empty items are
null
, undefined
, {}
, []
, and ""
Examples
Empty
[],
{},
[undefined],
[null],
[[], [], []],
[{},,[],[[[null],[undefined]],[,,,,,]],
new Array(10),
null,
undefined,
""
Not empty
[0]
[{A:null}],
{A:undefined},
[,,,0],
[[], [], [1]],
[{},,[],[[[1],[]],[]],
(new Array(10))[1] = 0,
false,
true,
" ",
Rewrite
With the above assumptions you can rewrite the code as a two functions.
As a non empty object mean we return false, and thus we do not need to iterate its values.
The entry point is isItemEmpty
you would call it as you did isDeepEmpty
const isObjEmpty = obj => obj === null || Object.keys(obj).length === 0;
const isItemEmpty = item => item === undefined || item === "" ||
(Array.isArray(item) && item.every(isItemEmpty)) ||
(typeof item === "object" && isObjEmpty(item));
Usage
isItemEmpty([{},[],[[]]]); // returns true
isItemEmpty([{A:0},[],[[]]]); // returns false
isItemEmpty(""); // returns true
true
if any item is!= true
egisDeepEmpty([0])
and which to me seams wrong, Could you be more specific in regards to what you mean by empty. \$\endgroup\$isEmpty()
function inside yourisDeepEmpty()
function. Why don't you? Please note that Code Review is only for code that is actually working. It says so in the How to Ask box, when you ask a question. \$\endgroup\$