We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if Object Instance of Class

Difficulty: Medium


Problem Description

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.

Key Insights

  • An object is considered an instance of a class if it is created from that class or any of its subclasses.
  • Primitive types should also be checked, as they can be considered instances of their corresponding wrapper classes.
  • The instanceof operator will not suffice for this problem, as it does not account for primitive types.
  • Special cases include checking for undefined, which should return false for any class checks.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)

Solution

To solve this problem, we will create a function that:

  1. Validates if the input value is an object or a primitive type.
  2. For objects, it will check if the prototype chain of the object includes the prototype of the given class.
  3. For primitive types like numbers, we will check if the value is of that type using typeof and ensure it corresponds to the class methods.

We will use the Object.getPrototypeOf() method to traverse the prototype chain until we either find a match or reach the end of the chain.


Code Solutions

function checkIfInstanceOf(obj, classFunction) {
    // Check if the classFunction is a function and obj is not null
    if (typeof classFunction !== 'function' || obj == null) {
        return false;
    }
    
    // Traverse the prototype chain
    let prototype = Object.getPrototypeOf(obj);
    while (prototype) {
        if (prototype === classFunction.prototype) {
            return true;
        }
        prototype = Object.getPrototypeOf(prototype);
    }
    
    return false;
}
← Back to All Questions