Infinite Method Object Problem
#2690
Description
LeetCode Problem 2690.
Write a function that returns an infinite-method object.
An infinite-method object is defined as an object that allows you to call any method and it will always return the name of the method.
For example, if you execute obj.abc123(), it will return "abc123".
Example 1:
Input: method = "abc123"
Output: "abc123"
Explanation:
const obj = createInfiniteObject();
obj['abc123'](); // "abc123"
The returned string should always match the method name.
Example 2:
Input: method = ".-qw73n|^2It"
Output: ".-qw73n|^2It"
Explanation: The returned string should always match the method name.
Constraints:
0 <= method.length <= 1000
Solution
Approach: Proxy with a get trap
The object must answer to every property name, so a fixed object cannot work. A Proxy with a get trap intercepts every property read: for any name it returns a function that, when called, returns that name as a string. String(prop) also copes with symbol keys, which Proxy traps receive as symbols.
Complexity: Time O(1) per call, space O(1).
var createInfiniteObject = function () {
return new Proxy(
{},
{
// obj.anything -> a function returning "anything"
get: (_target, prop) => () => String(prop),
},
);
};