Destructuring based on access

up: JavaScript

Antfu: Destructuring… with object or array?

Untested code from ChatGPT

function getHtml() {
  const string = "string content";
  const object = { main: "foo", intro: "bar" };
 
  // Create a proxy to handle the destructuring
  return new Proxy(
    {},
    {
      get(target, prop) {
        // If the property accessed is part of the object, return the object
        if (prop in object) {
          return object[prop];
        }
        // Otherwise, return the string
        return string;
      },
      ownKeys(target) {
        return Object.keys(object);
      },
      getOwnPropertyDescriptor(target, prop) {
        return {
          enumerable: true,
          configurable: true
        };
      }
    }
  );
}
 
// Usage examples
const html = getHtml(); // should be "string content"
console.log(html); // "string content"
 
const { main, intro } = getHtml(); // should be {main: "foo", intro: "bar"}
console.log(main); // "foo"
console.log(intro); // "bar"