We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Call Function with Custom Context

Number: 2790

Difficulty: Medium

Paid? No

Companies: N/A


Problem Description

Enhance the Function prototype by adding a callPolyfill method that accepts an object to be used as the function's this context and any number of additional arguments. When invoked, the function should run with the provided context, similar to the built-in call method—but without using it.


Key Insights

  • Extend the Function prototype to add a custom method.
  • Use a temporary unique property on the provided context object to attach the function.
  • Leverage the spread operator to pass arbitrary arguments.
  • Clean up the temporary property immediately after executing the function.

Space and Time Complexity

Time Complexity: O(1) per call
Space Complexity: O(1) (only a temporary property is added)


Solution

The solution works by temporarily adding the function (referred to as this inside callPolyfill) as a method on the context object using a unique key (via Symbol to avoid collisions). Once attached, the function is invoked with the provided arguments so that the context is correctly set. After the call, the temporary property is deleted from the context, and the result of the function call is returned.


Code Solutions

# In Python, the concept of 'this' does not exist.
# We simulate callPolyfill behavior by explicitly passing the object as the first argument.
def call_polyfill(func, obj, *args, **kwargs):
    # Call the function with obj as the first argument (simulating 'this')
    return func(obj, *args, **kwargs)

# Example usage:
class Item:
    def __init__(self, item):
        self.item = item

def tax(self, price, tax_rate):
    total_cost = price * (1 + tax_rate)
    return "The cost of {} is {}".format(self.item, total_cost)

# Create an object with the necessary context
burger = Item("burger")
result = call_polyfill(tax, burger, 10, 0.1)
print(result)  # Output: "The cost of burger is 11.0"
← Back to All Questions