Skip to content

2693. Call Function with Custom Context

Description

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:

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.

Β 

Example 1:

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:

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 <= 105

Solutions

Solution 1

 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
 */

Comments