LeetCode Problem Workspace

Check if Object Instance of Class

Implement a function to check if an object is an instance of a specific class or its superclass in JavaScript.

category

0

Topics

code_blocks

1

Code langs

hub

0

Related

Practice Focus

Medium · Check if Object Instance of Class core interview pattern

bolt

Answer-first summary

Implement a function to check if an object is an instance of a specific class or its superclass in JavaScript.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Check if Object Instance of Class core interview pattern

Try AiBox Copilotarrow_forward

This problem tests your ability to check if an object is an instance of a class or a superclass. You need to implement a function that checks whether a given object is an instance of the provided class, accounting for inheritance through the prototype chain.

Problem Statement

Given a value and a class, determine if the value is an instance of that class or a subclass of it. This can be achieved by checking whether the object in question has access to the class's methods.

The solution should handle edge cases where the value or class might be undefined. The function must return true if the object is an instance, and false otherwise.

Examples

Example 1

Input: func = () => checkIfInstanceOf(new Date(), Date)

Output: true

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

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

A date constructor cannot logically be an instance of itself.

Constraints

Solution Approach

Using instanceof Operator

The simplest approach is to use JavaScript's built-in instanceof operator. This operator checks whether an object is an instance of a specified class or its subclass by following the prototype chain.

Custom Prototype Chain Traversal

Alternatively, we can manually traverse the prototype chain of the object to see if it matches the prototype of the class. This method gives more flexibility but requires careful handling of the prototype chain.

Handling Undefined Values

It's important to handle cases where either the class or the value is undefined. The function should return false in these cases, as an undefined class or object cannot form a valid relationship.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

The time complexity of the solution depends on how we traverse the prototype chain. In the case of instanceof, the operation is typically O(n), where n is the number of prototypes in the inheritance chain. Space complexity is O(1) as no extra space is required beyond the input objects.

What Interviewers Usually Probe

  • Candidate's ability to handle inheritance and prototype chains in JavaScript.
  • Understanding of how instanceof works in JavaScript and potential pitfalls.
  • Ability to manage edge cases, such as undefined values or circular references in inheritance.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting that instanceof will check both the class and its parent classes, which can lead to incorrect results if not handled properly.
  • Failing to account for edge cases where the class or the object might be undefined.
  • Misunderstanding the difference between a class constructor and an object instance, leading to incorrect checks.

Follow-up variants

  • Consider whether the class check should apply only to the direct class or include all superclasses.
  • Handle cases where the object might have a custom prototype chain.
  • Explore the behavior when the provided value is an array, function, or other special object types.

FAQ

What is the best approach to check if an object is an instance of a class?

Using the instanceof operator is the most straightforward approach in JavaScript. It checks the prototype chain and works well for most use cases.

What should I do if the class or value is undefined?

In these cases, the function should return false, as an undefined class or object can't logically be part of an instance relationship.

How does JavaScript's prototype chain work in this problem?

The prototype chain is a mechanism where objects can inherit properties and methods from other objects. When checking if an object is an instance, JavaScript follows the prototype chain to verify if the class or any of its superclasses is involved.

Can I check if a constructor is an instance of itself?

No, a constructor cannot be an instance of itself, as seen in the example where checkIfInstanceOf(Date, Date) returns false.

How does GhostInterview help with this problem?

GhostInterview offers solutions that guide you through understanding the prototype chain and avoiding common mistakes with instanceof and manual checks.

terminal

Solution

Solution 1

#### TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function checkIfInstanceOf(obj: any, classFunction: any): boolean {
    if (classFunction === null || classFunction === undefined) {
        return false;
    }
    while (obj !== null && obj !== undefined) {
        const proto = Object.getPrototypeOf(obj);
        if (proto === classFunction.prototype) {
            return true;
        }
        obj = proto;
    }
    return false;
}

/**
 * checkIfInstanceOf(new Date(), Date); // true
 */
Check if Object Instance of Class Solution: Check if Object Instance of Class cor… | LeetCode #2618 Medium