Explorer
JavaScript

Write a function `myCall(fn, context, ...args)` that works like Function.prototype.call.

Problem Statement

<p>Write a function <code>myCall(fn, context, ...args)</code> that works like Function.prototype.call.</p>

Examples

Input: myCall(fn, ctx, 1, 2)

Output: fn invoked with context ctx and arguments 1, 2

Explanation: Simulates Function.prototype.call.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: call invokes a function with a specific "this" and individual arguments. šŸ’” Hint 2: Temporarily attach the function to the context object, call it, then delete it. šŸ’” Hint 3: Use a Symbol as the property key to avoid collisions.

Editorial & Approach

Problem Overview & Intuition

To solve Implement Call, we consider the execution characteristics of JavaScript engines. Write a function `myCall(fn, context, ...args)` that works like Function.prototype.call. 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 (call invokes a function with a specific "this" and individual arguments).
  3. Implement Logic: Handle state and transformations efficiently (temporarily attach the function to the context object, call it, then delete it).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function myCall(fn, context, ...args) {
  context = context || globalThis;
  const sym = Symbol("fn");
  context[sym] = fn;
  const result = context[sym](...args);
  delete context[sym];
  return result;
}

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 Call

Hard

Write a function myCall(fn, context, ...args) that works like Function.prototype.call.

Example Scenarios
1Example 1
Input: myCall(fn, ctx, 1, 2)
Output: fn invoked with context ctx and arguments 1, 2
Explanation:

Simulates Function.prototype.call.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
Hey Bob