jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
27 stars 4 forks source link

IsEmpty #13

Closed albinAppsmith closed 7 months ago

albinAppsmith commented 7 months ago

Info

difficulty: medium
title: IsEmpty
template: javascript
tags: javascript, lodash

Question

Write a JavaScript function called isEmpty that takes a single argument and checks if it represents an empty object, collection, map, or set. The function should return true if the input is empty and false otherwise.

Example:

isEmpty({}); // true
isEmpty([]); // true
isEmpty(new Map()); // true
isEmpty(new Set()); // true

isEmpty({name: 'John'}); // false
isEmpty([1, 2, 3]); // false
isEmpty(new Map([['a', 1], ['b', 2]])); // false
isEmpty(new Set([1, 2, 3])); // false

Template

index.js

export function isEmpty(value) {
  // your answer here
}

index.test.js

import { isEmpty } from './';

describe('isEmpty function', () => {
    it('should return true for empty objects, arrays, maps, and sets', () => {
        expect(isEmpty({})).toBe(true);
        expect(isEmpty([])).toBe(true);
        expect(isEmpty(new Map())).toBe(true);
        expect(isEmpty(new Set())).toBe(true);
    });

    it('should return false for non-empty objects, arrays, maps, and sets', () => {
        expect(isEmpty({ name: 'John' })).toBe(false);
        expect(isEmpty([1, 2, 3])).toBe(false);
        expect(isEmpty(new Map([['a', 1], ['b', 2]]))).toBe(false);
        expect(isEmpty(new Set([1, 2, 3]))).toBe(false);
    });

    it('should return true for null and undefined', () => {
        expect(isEmpty(null)).toBe(true);
        expect(isEmpty(undefined)).toBe(true);
    });

    it('should return true for other non-object values', () => {
        expect(isEmpty(0)).toBe(true);
        expect(isEmpty('')).toBe(true);
        expect(isEmpty(false)).toBe(true);
    });
});
github-actions[bot] commented 7 months ago

14 - Pull Request updated.