Check if Object Instance of Class Problem
Description
LeetCode Problem 2618.
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()".
Solution
Approach: Walk the prototype chain
instanceof is not enough: it returns false for primitives such as 5 with Number, and it throws if the right side is not callable. The problem defines an instance as an object that can reach the class's methods, i.e. one whose prototype chain contains classFunction.prototype.
- If
classFunctionis not a function (for exampleundefined), returnfalse. - If
objisnullorundefinedthere is no chain, so returnfalse. Otherwise wrap it withObject(obj)so primitives get their wrapper's prototype (5then hasNumber.prototype). - Start at the object's prototype and follow
Object.getPrototypeOfuntil it isnull, returningtruewhen a link equalsclassFunction.prototype.
A class constructor such as Date itself is not an instance of Date: its chain is Function.prototype, then Object.prototype, which does not include Date.prototype. An object created with Object.create(null) has no chain at all and gives false.
Complexity: time O(d) for a prototype chain of depth d, space O(1).
/**
* @param {*} obj
* @param {*} classFunction
* @return {boolean}
*/
var checkIfInstanceOf = function (obj, classFunction) {
if (typeof classFunction !== "function") return false;
let proto = obj === null || obj === undefined ? null : Object.getPrototypeOf(Object(obj));
while (proto !== null) {
if (proto === classFunction.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
};