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

Number: 2758

Difficulty: Medium

Paid? No

Companies: Google, Amazon


Problem Description

Implement a function that, given any value and a class (or constructor function), determines whether the value is considered an “instance” of that class. In this context, a value is an instance of a class if it has access to the class’s methods (which in JavaScript is determined by the prototype chain). Note that even primitive values (like 5) are considered instances of their corresponding wrapper types (Number in this case), and special cases (for example, a constructor function can’t be an instance of itself) must be handled.


Key Insights

  • The solution must work with any value, including primitives, objects, functions, and even undefined.
  • For JavaScript, checking the prototype chain is key: if the target class’s prototype appears in the value’s prototype chain then the value “inherits” its methods.
  • Primitives (like numbers or strings) in JavaScript can access methods of their wrapper objects.
  • The function should safely handle cases when the provided class is not a valid constructor or when the value is null/undefined.
  • Although the core idea is similar to the built-in “instanceof” operator in JavaScript, its limitations (e.g. failing on boxed primitives) mean a custom check is necessary.

Space and Time Complexity

Time Complexity: O(d) where d is the depth of the prototype (or inheritance) chain. Space Complexity: O(1)


Solution

The solution involves “boxing” primitive values when necessary (in JavaScript, calling Object(value) ensures a primitive is treated as an object so its prototype chain can be inspected). Then, by iterating through the prototype chain starting from the provided object, the algorithm checks if any link in that chain is equal to the target class’s prototype. If found, the function returns true. Otherwise, it returns false. Special cases – such as when the target class isn’t a function or when the value is null – must be handled appropriately. Similar ideas are applied in other languages (using built-in type checking, RTTI/dynamic_cast in C++, or the instanceof / isInstance methods), though the details differ by language.


Code Solutions

# Python version:
# Note: Python does not have prototypes like JavaScript.
# Here, we simulate the behavior using the built-in isinstance check,
# which covers inheritance. This works for primitives and custom classes alike.
def checkIfInstanceOf(value, target_class):
    # Check if target_class is a type; if not, it cannot be used for instance checking.
    if not isinstance(target_class, type):
        return False
    # Use isinstance, which internally checks the method resolution order (inheritance chain).
    return isinstance(value, target_class)

# Example usage:
if __name__ == "__main__":
    # Example 1: Check with datetime (similar to Date in JS)
    from datetime import datetime
    print(checkIfInstanceOf(datetime.now(), datetime))  # Expected output: True

    # Example 2: Inheritance example with custom classes
    class Animal:
        pass
    class Dog(Animal):
        pass
    print(checkIfInstanceOf(Dog(), Animal))  # Expected output: True

    # Example 3: A class should not be an instance of itself
    print(checkIfInstanceOf(datetime, datetime))  # Expected output: False

    # Example 4: Primitive number is considered an instance of int
    print(checkIfInstanceOf(5, int))  # Expected output: True
← Back to All Questions