diff --git a/object/isEmptyObjectLiteral.js b/object/isEmptyObjectLiteral.js new file mode 100644 index 0000000..9c1b0b1 --- /dev/null +++ b/object/isEmptyObjectLiteral.js @@ -0,0 +1,22 @@ +/** + * Checks if the given object is an empty object literal. + * An empty object literal is defined as an object with no own properties + * and whose prototype is `Object.prototype`. + * @param {object} obj - The object to check. + * @returns {boolean} - Returns `true` if the object is an empty object literal, otherwise `false`. + * @example + * isEmptyObjectLiteral({}); // true + * isEmptyObjectLiteral(Object.create({})); // true + * isEmptyObjectLiteral({ a: 1 }); // false + * isEmptyObjectLiteral([]); // false + * isEmptyObjectLiteral(null); // false + * isEmptyObjectLiteral(Object.create(null)); // false + */ +export default function isEmptyObjectLiteral(obj) { + return ( + obj !== null && + typeof obj === 'object' && + Array.isArray(obj) === false && + Object.keys(obj).length === 0 + ); +} diff --git a/test/specs/index.js b/test/specs/index.js index eb7089a..0f846cc 100644 --- a/test/specs/index.js +++ b/test/specs/index.js @@ -40,6 +40,7 @@ import('./object/filter.spec.js'); import('./object/getNestedValue.spec.js'); import('./object/hasBinary.spec.js'); import('./object/instanceOf.spec.js'); +import('./object/isEmptyObjectLiteral.spec.js'); import('./object/isPromise.spec.js'); import('./object/isSame.spec.js'); import('./object/merge.spec.js'); diff --git a/test/specs/object/isEmptyObjectLiteral.spec.js b/test/specs/object/isEmptyObjectLiteral.spec.js new file mode 100644 index 0000000..9ddee32 --- /dev/null +++ b/test/specs/object/isEmptyObjectLiteral.spec.js @@ -0,0 +1,19 @@ +import isEmptyObjectLiteral from '../../../object/isEmptyObjectLiteral.js'; + +describe('object/isEmptyObjectLiteral', () => { + + it('should determine whether object is an empty object literal, aka `{}`', () => { + + // ok + expect(isEmptyObjectLiteral({})).to.equal(true); + expect(isEmptyObjectLiteral(Object.create({}))).to.equal(true); + expect(isEmptyObjectLiteral(Object.create(null))).to.equal(true); + + // not ok + expect(isEmptyObjectLiteral({a: 1})).to.equal(false); + expect(isEmptyObjectLiteral([])).to.equal(false); + expect(isEmptyObjectLiteral(null)).to.equal(false); + + }); + +});