Problem

Enhance all functions to have the callPolyfill method. The method accepts an object obj as its first parameter and any number of additional arguments. The obj becomes the this context for the function. The additional arguments are passed to the function (that the callPolyfill method belongs on).

For example if you had the function:

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

Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is because the this context was not defined.

However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The cost of salad is 11". The this context was appropriately set, and the function logged an appropriate output.

Please solve this without using the built-in Function.call method.

Examples

Example 1

1
2
3
4
5
6
7
8
9
Input:
fn = function add(b) {
  return this.a + b;
}
args = [{"a": 5}, 7]
Output: 12
Explanation:
fn.callPolyfill({"a": 5}, 7); // 12
callPolyfill sets the "this" context to {"a": 5}. 7 is passed as an argument.

Example 2

1
2
3
4
5
6
7
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"
Explanation: 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 <= 10^5

Solution

Method 1 – Attach to Function Prototype and Use Temporary Property

Intuition

To simulate the call method without using Function.call, we can temporarily assign the function as a property of the context object, call it, and then remove the property. This ensures the function executes with the correct this value.

Approach

  1. Add a method callPolyfill to Function.prototype.
  2. In callPolyfill, assign the function (this) as a temporary property on the context object.
  3. Call the function with the provided arguments, using the context as this.
  4. Delete the temporary property after calling.
  5. Return the result.

Code

1
2
3
4
5
6
7
8
Function.prototype.callPolyfill = function(obj, ...args) {
  obj = obj || globalThis;
  const fnKey = Symbol();
  obj[fnKey] = this;
  const ans = obj[fnKey](...args);
  delete obj[fnKey];
  return ans;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
declare global {
  interface Function {
    callPolyfill(obj: any, ...args: any[]): any;
  }
}

Function.prototype.callPolyfill = function(obj: any, ...args: any[]): any {
  obj = obj || globalThis;
  const fnKey = Symbol();
  obj[fnKey] = this;
  const ans = obj[fnKey](...args);
  delete obj[fnKey];
  return ans;
};

Complexity

  • ⏰ Time complexity: O(1)
  • 🧺 Space complexity: O(1)