Problem

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".

Examples

Example 1:

1
2
3
4
5
6
Input: method = "abc123"
Output: "abc123"
Explanation:
const obj = createInfiniteObject();
obj['abc123'](); // "abc123"
The returned string should always match the method name.

Example 2:

1
2
3
Input: method = ".-qw73n|^2It"
Output: ".-qw73n|^2It"
Explanation: The returned string should always match the method name.

Constraints:

  • 0 <= method.length <= 1000

Solution

Method 1 – Proxy Trap for Any Method

Intuition

We want an object that can respond to any method call and always returns the method name. Using a Proxy, we can intercept any property access and return a function that returns the property name.

Approach

  1. Use a Proxy to intercept any property access on the object.
  2. For any property (method) accessed, return a function that returns the property name when called.
  3. This works for any method name, including dynamically generated ones.

Code

1
2
3
4
5
function createInfiniteObject() {
  return new Proxy({}, {
    get: (_, prop) => () => prop.toString()
  });
}
1
2
3
4
5
function createInfiniteObject(): any {
  return new Proxy({}, {
    get: (_, prop: string | symbol) => () => prop.toString()
  });
}

Complexity

  • ⏰ Time complexity: O(1) — Each method call is intercepted and handled in constant time.
  • 🧺 Space complexity: O(1) — No extra storage is used beyond the proxy itself.