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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (call invokes a function with a specific "this" and individual arguments).
- Implement Logic: Handle state and transformations efficiently (temporarily attach the function to the context object, call it, then delete it).
- 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.