Explorer
JavaScript

Write a function `myInstanceOf(obj, Constructor)` that checks if obj is an instance of Constructor by traversing the prototype chain.

Problem Statement

<p>Write a function <code>myInstanceOf(obj, Constructor)</code> that checks if obj is an instance of Constructor by traversing the prototype chain.</p>

Examples

Input: myInstanceOf(new Date(), Date)

Output: true

Explanation: Traverses prototype chain to find Constructor.prototype.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: instanceof checks if Constructor.prototype exists in the prototype chain of obj. šŸ’” Hint 2: Use Object.getPrototypeOf() to traverse up the chain. šŸ’” Hint 3: Loop: if proto === Constructor.prototype return true. If proto is null, return false. Otherwise, go up.

Editorial & Approach

Problem Overview & Intuition

To solve Implement instanceof, we consider the execution characteristics of JavaScript engines. Write a function `myInstanceOf(obj, Constructor)` that checks if obj is an instance of Constructor by traversing the prototype chain. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (instanceof checks if constructor.prototype exists in the prototype chain of obj).
  3. Implement Logic: Handle state and transformations efficiently (use object.getprototypeof() to traverse up the chain).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function myInstanceOf(obj, Constructor) {
  if (obj === null || typeof obj !== "object") return false;
  let proto = Object.getPrototypeOf(obj);
  while (proto !== null) {
    if (proto === Constructor.prototype) return true;
    proto = Object.getPrototypeOf(proto);
  }
  return false;
}

Complexity Analysis

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Implement instanceof

Hard

Write a function myInstanceOf(obj, Constructor) that checks if obj is an instance of Constructor by traversing the prototype chain.

Example Scenarios
1Example 1
Input: myInstanceOf(new Date(), Date)
Output: true
Explanation:

Traverses prototype chain to find Constructor.prototype.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[true,true,false,false]