LeetCode Problem Workspace

Call Function with Custom Context

Learn to implement a callPolyfill method that correctly sets a function's this context and passes arguments properly.

category

0

Topics

code_blocks

1

Code langs

hub

0

Related

Practice Focus

Medium · Call Function with Custom Context core interview pattern

bolt

Answer-first summary

Learn to implement a callPolyfill method that correctly sets a function's this context and passes arguments properly.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Call Function with Custom Context core interview pattern

Try AiBox Copilotarrow_forward

This problem focuses on implementing a callPolyfill method that allows any function to execute with a specified this context and arguments. You must handle the first argument as the new this and apply remaining arguments to the original function. Correctly managing context and argument order is essential for passing all test cases in JavaScript interview scenarios.

Problem Statement

Enhance all JavaScript functions with a callPolyfill method. The method accepts an object obj as the first parameter, which becomes the this context, followed by any number of arguments to pass into the function. Your implementation must ensure that the original function executes correctly with this customized context and arguments.

For example, calling a function tax(10, 0.1) without setting this will produce undefined behavior. Using callPolyfill with an object {item: 'burger'} ensures that inside the function, this.item refers to 'burger', and additional parameters are correctly passed to calculate results.

Examples

Example 1

Input: See original problem statement.

Output: See original problem statement.

function tax(price, taxRate) { const totalCost = price * (1 + taxRate); console.log(The cost of this.itemis{this.item} is {totalCost}); }

Example 2

Input: fn = function add(b) { return this.a + b; } args = [{"a": 5}, 7]

Output: 12

fn.callPolyfill({"a": 5}, 7); // 12 callPolyfill sets the "this" context to {"a": 5}. 7 is passed as an argument.

Example 3

Input: fn = function tax(price, taxRate) { return The cost of the ${this.item} is ${price * taxRate}; } args = [{"item": "burger"}, 10, 1.1]

Output: "The cost of the burger is 11"

callPolyfill sets the "this" context to {"item": "burger"}. 10 and 1.1 are passed as additional arguments.

Constraints

  • typeof args[0] == 'object' and args[0] != null
  • 1 <= args.length <= 100
  • 2 <= JSON.stringify(args[0]).length <= 105

Solution Approach

Assign temporary property to manage context

Attach the original function as a temporary property on the obj argument. This allows execution using obj as the this context, ensuring that this inside the function references obj.

Apply arguments correctly

Extract all arguments after the first one and pass them to the function using spread syntax. This ensures the function receives its intended parameters while maintaining the custom this binding.

Clean up after execution

After calling the function with the temporary property, remove the property from obj to avoid polluting the object. Return the function's output as the result of callPolyfill.

Complexity Analysis

Metric Value
Time **
Space **

Time complexity is O(n) where n is the number of arguments because they are iterated when applying to the function. Space complexity is O(1) extra, aside from the temporary property created on obj.

What Interviewers Usually Probe

  • Expect candidates to handle dynamic this binding and argument application.
  • Look for proper cleanup of temporary properties to avoid side effects.
  • Watch for understanding of function context and how JavaScript call/apply patterns work.

Common Pitfalls or Variants

Common pitfalls

  • Failing to use the first argument as this context correctly.
  • Not passing remaining arguments in the proper order, causing incorrect results.
  • Leaving temporary properties on obj, which may modify the object unexpectedly.

Follow-up variants

  • Implement applyPolyfill to accept an array of arguments instead of individual arguments.
  • Support functions that return values versus just logging output.
  • Handle primitive types for this by wrapping them in their object equivalents.

FAQ

What is the main purpose of callPolyfill?

callPolyfill lets a function execute with a specified this context and passes any additional arguments correctly.

Can callPolyfill handle primitive types as this?

Yes, primitives are converted to their object equivalents so the function can safely access properties.

Why is removing the temporary property important?

Leaving the temporary property would modify obj, potentially causing side effects in later code.

How does callPolyfill differ from Function.prototype.call?

callPolyfill mimics call by manually setting this and passing arguments, useful for understanding context binding internally.

Is callPolyfill useful for interview preparation?

Yes, it tests understanding of function context, argument handling, and JavaScript object behavior, which are common interview topics.

terminal

Solution

Solution 1

#### TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
declare global {
    interface Function {
        callPolyfill(context: Record<any, any>, ...args: any[]): any;
    }
}

Function.prototype.callPolyfill = function (context, ...args): any {
    const fn = this.bind(context);
    return fn(...args);
};

/**
 * function increment() { this.count++; return this.count; }
 * increment.callPolyfill({count: 1}); // 2
 */
Call Function with Custom Context Solution: Call Function with Custom Context cor… | LeetCode #2693 Medium