LeetCode 2693: Call Function with Custom Context
Problem Description
Explanation
To implement the callPolyfill
method, we need to create a function that takes an object obj
as its first parameter and any number of additional arguments. This object obj
will become the this
context for the function, and the additional arguments will be passed to the function. We will achieve this by creating a higher-order function that returns a new function with the desired behavior. The new function will use the object obj
as its this
context and call the original function with the provided arguments.
Algorithmic Idea
- Create a higher-order function
callPolyfill
that takes the original functionfn
as input. - Return a new function that:
- Accepts the object
obj
and additional argumentsargs
. - Binds the object
obj
as thethis
context using theapply
method. - Calls the original function
fn
with the boundthis
context and the additional arguments.
- Accepts the object
Time Complexity
The time complexity of this solution is O(1) as it directly calls the original function with the provided arguments.
Space Complexity
The space complexity of this solution is O(1) as it does not use any extra space proportional to the input size.
Solutions
import java.util.function.Function;
class Solution {
public static Function<Object, Object> callPolyfill(Function<Object, Object> fn) {
return obj -> {
Object[] args = (Object[]) obj;
return fn.apply(args[0], (Object[]) Arrays.copyOfRange(args, 1, args.length));
};
}
}
Loading editor...