Explorer
JavaScript

Write a function `myBind(fn, context, ...boundArgs)` that works like Function.prototype.bind.

Problem Statement

<p>Write a function <code>myBind(fn, context, ...boundArgs)</code> that works like Function.prototype.bind.</p>

Examples

Input: const bound = myBind(fn, ctx, 1); bound(2);

Output: fn called with context ctx and args (1, 2)

Explanation: Simulates Function.prototype.bind.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: bind returns a new function with a fixed "this" and optional pre-filled arguments. šŸ’” Hint 2: Use fn.apply(context, args) to call with the correct context. šŸ’” Hint 3: Return a function that merges boundArgs with later args.

Editorial & Approach

Problem Overview & Intuition

To solve Implement Bind, we consider the execution characteristics of JavaScript engines. Write a function `myBind(fn, context, ...boundArgs)` that works like Function.prototype.bind. 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 (bind returns a new function with a fixed "this" and optional pre-filled arguments).
  3. Implement Logic: Handle state and transformations efficiently (use fn.apply(context, args) to call with the correct context).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function myBind(fn, context, ...boundArgs) {
  return function(...laterArgs) {
    return fn.apply(context, [...boundArgs, ...laterArgs]);
  };
}

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 Bind

Hard

Write a function myBind(fn, context, ...boundArgs) that works like Function.prototype.bind.

Example Scenarios
1Example 1
Input: const bound = myBind(fn, ctx, 1); bound(2);
Output: fn called with context ctx and args (1, 2)
Explanation:

Simulates Function.prototype.bind.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
Hello, Alice!