2693. Вызов функции с пользовательским контекстом (Medium) (https://leetcode.com/problems/call-function-with-custom-context/)
Расширьте все функции методом callPolyfill. Метод принимает объект obj в качестве первого параметра и любое количество дополнительных аргументов. obj становится контекстом this для функции. Дополнительные аргументы передаются в функцию, которой принадлежит метод callPolyfill. Решите задачу без использования встроенного метода Function.call. Ограничения: - typeof args[0] == “object” и args[0] != null - 1 <= args.length <= 100 - 2 <= JSON.stringify(args[0]).length <= 10
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }
interface Function {
callPolyfill: (context: Record<string, JSONValue>, ...args: JSONValue[]) => JSONValue
}
/* Временно делаем функцию методом объекта */
Function.prototype.callPolyfill = function (context, ...args): JSONValue {
let object = { ...context } as any
let symbol = Symbol("context")
// this здесь — это функция
object[symbol] = this
// Вызываем add как метод object
return object[symbol](...args)
}
// Локальная проверка:
function add(this: { a: number }, b: number) {
return this.a + b
}
console.log(add.callPolyfill({ a: 5 }, 7)) // 12
export {}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.