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:
- Validates if the input value is an object or a primitive type.
- For objects, it will check if the prototype chain of the object includes the prototype of the given class.
- 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.