#2693
Call Function with Custom Context
MediumFunction BindingContext Management
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach utilizes JavaScript's built-in ability to bind context without using the built-in call method. We create a new function that sets 'this' correctly and calls the original function efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Define a method on Function prototype called callPolyfill.
- 2Step 2: Inside this method, use 'apply' to call the function with the provided context and arguments.
- 3Step 3: Return the result of the function call.
solution.py7 lines
1def call_polyfill(fn, context, *args):
2 return fn(*args)
3
4# Example usage
5fn = lambda b: context['a'] + b
6context = {'a': 5}
7print(call_polyfill(fn, context, 7)) # Output: 12ℹ
Complexity note: The complexity is O(n) because we are directly passing the arguments without unnecessary iterations.
- 1Understanding context in JavaScript is crucial for function execution.
- 2Using apply or bind can simplify context management.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.