I am currently exploring ways to develop a solution using plain JS (without relying on any external libraries) that can determine whether a given input is considered 'empty' or not.
Below are the code snippets and test cases I have prepared for this purpose, with expected outcomes specified as comments alongside each test case.
Despite my efforts in creating functions to thoroughly validate these assertions on stackblitz, I have yet to achieve complete coverage.
https://stackblitz.com/edit/node-ksxnjm
const assert = require('assert');
function isEmpty(obj) {
return Object.keys(obj).every((k) => !Object.keys(obj[k]).length);
}
const test1 = {}; // expect true
const test2 = { some: 'value' }; // expect false
const test3 = { some: {} }; // expect true
const test4 = []; // expect true
const test5 = [[]]; // expect true
const test6 = { some: [] }; // expect true
const test7 = { some: ['barry'] }; // expect false
const test8 = { some: new Map() }; // expect true
const test9 = {
response: new Map([['body', new Map([['something', {}]])]]),
}; // expect true
const test10 = {
response: '{"body":{"something":{}}}',
}; // expect true
const test11 = {
something: { somethingElse: {} },
}; // expect true
assert.strictEqual(isEmpty(test1), true);
assert.strictEqual(isEmpty(test2), false);
assert.strictEqual(isEmpty(test3), true);
assert.strictEqual(isEmpty(test4), true);
assert.strictEqual(isEmpty(test5), true);
assert.strictEqual(isEmpty(test6), true);
assert.strictEqual(isEmpty(test7), false);
assert.strictEqual(isEmpty(test8), true);
assert.strictEqual(isEmpty(test9), true);
assert.strictEqual(isEmpty(test10), true);
assert.strictEqual(isEmpty(test11), true);
While my current function adequately handles most of the provided test cases, it falls short when dealing with nested objects and stringified objects. I find myself at an impasse on how to address this issue.
What approach should I take to accommodate these specific scenarios?
EDIT:
const test12 = {
something: {
somethingElse: {
number: 1,
someSet: new Set(['garry']),
},
},
}; // should evaluate to false
const test13 = new Map([
['something', new Map([
['somethingElse', new Map([
['number', 1],
['someSet', new Set(['garry'])]
])]
])]
]); // should also evaluate to false