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
21 stars 4 forks source link

InstanceOfClass #32

Closed jsartisan closed 4 months ago

jsartisan commented 4 months ago

Info

difficulty: easy
title: InstanceOfClass
template: javascript
tags: javascript

Question

Implement a function that verifies whether an object is an instance of a particular class. This function should take both the object and the class as parameters.

class A {}
class B extends A {}

let objB = new B()
instanceOfClass(objB , B) // true
instanceOfClass(objB, A) // true

class C {}
instanceOfClass(objB, C) // false

Template

index.js

export function instanceOfClass(obj, targetClass) {

}

index.test.js

import { instanceOfClass } from "./";

class Animal {}
class Dog extends Animal {}

describe('instanceOfClass function', () => {
  test('Object is an instance of the provided class', () => {
    const dog = new Dog();
    expect(instanceOfClass(dog, Dog)).toBe(true);
  });

  test('Object is not an instance of the provided class', () => {
    const animal = new Animal();
    expect(instanceOfClass(animal, Dog)).toBe(false);
  });

  test('Object is an instance of a parent class', () => {
    const dog = new Dog();
    expect(instanceOfClass(dog, Animal)).toBe(true);
  });

  test('Object is not an instance of a parent class', () => {
    const animal = new Animal();
    expect(instanceOfClass(animal, Dog)).toBe(false);
  });

  test('Null object should not be instance of any class', () => {
    const nullObj = null;
    expect(instanceOfClass(nullObj, Object)).toBe(false);
  });
});
github-actions[bot] commented 4 months ago

33 - Pull Request updated.