รหัสบน GitHub
const isEmpty = value => (
(!value && value !== 0 && value !== false)
|| (Array.isArray(value) && value.length === 0)
|| (isObject(value) && Object.keys(value).length === 0)
|| (typeof value.size === 'number' && value.size === 0)
// `WeekMap.length` is supposed to exist!?
|| (typeof value.length === 'number'
&& typeof value !== 'function' && value.length === 0)
);
// Source: https://levelup.gitconnected.com/javascript-check-if-a-variable-is-an-object-and-nothing-else-not-an-array-a-set-etc-a3987ea08fd7
const isObject = value =>
Object.prototype.toString.call(value) === '[object Object]';
การทดสอบของคนจน😁
const test = () => {
const run = (label, values, expected) => {
const length = values.length;
console.group(`${label} (${length} tests)`);
values.map((v, i) => {
console.assert(isEmpty(v) === expected, `${i}: ${v}`);
});
console.groupEnd();
};
const empty = [
null, undefined, NaN, '', {}, [],
new Set(), new Set([]), new Map(), new Map([]),
];
const notEmpty = [
' ', 'a', 0, 1, -1, false, true, {a: 1}, [0],
new Set([0]), new Map([['a', 1]]),
new WeakMap().set({}, 1),
new Date(), /a/, new RegExp(), () => {},
];
const shouldBeEmpty = [
{undefined: undefined}, new Map([[]]),
];
run('EMPTY', empty, true);
run('NOT EMPTY', notEmpty, false);
run('SHOULD BE EMPTY', shouldBeEmpty, true);
};
ผลการทดสอบ:
EMPTY (10 tests)
NOT EMPTY (16 tests)
SHOULD BE EMPTY (2 tests)
Assertion failed: 0: [object Object]
Assertion failed: 1: [object Map]