Talentd
FleetCode

2618. Check if Object Instance of Class

Medium27.7% acceptance2 companies

Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods.

There are no constraints on the data types that can be passed to the function. For example, the value or the class could be undefined.

Example 1:

Input: func = () => checkIfInstanceOf(new Date(), Date)
Output: true
Explanation: The object returned by the Date constructor is, by definition, an instance of Date.

Example 2:

Input: func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); }
Output: true
Explanation:
class Animal {};
class Dog extends Animal {};
checkIfInstanceOf(new Dog(), Animal); // true

Dog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog and Animal.

Example 3:

Input: func = () => checkIfInstanceOf(Date, Date)
Output: false
Explanation: A date constructor cannot logically be an instance of itself.

Example 4:

Input: func = () => checkIfInstanceOf(5, Number)
Output: true
Explanation: 5 is a Number. Note that the "instanceof" keyword would return false. However, it is still considered an instance of Number because it accesses the Number methods. For example "toFixed()".

Asked at 2 companies

Hints open one at a time

Hint 1
In Javascript, inheritance is achieved with the prototype chain.
Hint 2
You can get the prototype of an object with the Object.getPrototypeOf(obj) function. Alternatively, you can code obj['__proto__'].
Hint 3
You can compare an object's __proto__ with classFunction.prototype.
Hint 4
Traverse the entire prototype chain until you find a match.
11:58
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1/**
2 * @param {*} obj
3 * @param {*} classFunction
4 * @return {boolean}
5 */
6var checkIfInstanceOf = function(obj, classFunction) {
7
8};
9
10/**
11 * checkIfInstanceOf(new Date(), Date); // true
12 */
Starter codeJavaScriptSpaces: 4
Examples
Input
() => checkIfInstanceOf(new Date(), Date)
Input
() => { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); }
Input
() => checkIfInstanceOf(Date, Date)
Input
() => checkIfInstanceOf(5, Number)
Your code is saved on this device.Solution