Skip to content

Commit b9d43d2

Browse files
committed
Add solution #2693
1 parent 9d1c9ed commit b9d43d2

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,7 @@
433433
2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy|
434434
2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy|
435435
2677|[Chunk Array](./2677-chunk-array.js)|Easy|
436+
2693|[Call Function with Custom Context](./2693-call-function-with-custom-context.js)|Medium|
436437
2695|[Array Wrapper](./2695-array-wrapper.js)|Easy|
437438
2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy|
438439
2704|[To Be Or Not To Be](./2704-to-be-or-not-to-be.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 2693. Call Function with Custom Context
3+
* https://leetcode.com/problems/call-function-with-custom-context/
4+
* Difficulty: Medium
5+
*
6+
* Enhance all functions to have the callPolyfill method. The method accepts an object obj as
7+
* its first parameter and any number of additional arguments. The obj becomes the this context
8+
* for the function. The additional arguments are passed to the function (that the callPolyfill
9+
* method belongs on).
10+
*
11+
* For example if you had the function:
12+
*
13+
* function tax(price, taxRate) {
14+
* const totalCost = price * (1 + taxRate);
15+
* console.log(`The cost of ${this.item} is ${totalCost}`);
16+
* }
17+
*
18+
* Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is
19+
* because the this context was not defined.
20+
*
21+
* However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The
22+
* cost of salad is 11". The this context was appropriately set, and the function logged an
23+
* appropriate output.
24+
*
25+
* Please solve this without using the built-in Function.call method.
26+
*/
27+
28+
/**
29+
* @param {Object} context
30+
* @param {Array} args
31+
* @return {null|boolean|number|string|Array|Object}
32+
*/
33+
Function.prototype.callPolyfill = function(context, ...args) {
34+
return this.bind(context)(...args);
35+
}

0 commit comments

Comments
 (0)