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.
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);
});
});
Info
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.
Template
index.js
index.test.js