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.