Proxy – (object always defined)

This uses a proxy to make sure all keys/props of an object are always defined.

let spec = {
  get: (o, key) => {
    return o[key] != null ? o[key] : o[key] = O();
  },
  set: (o, key, v) => {
    o[key] = v;
  }
};

let O = () => {
  return new Proxy({}, spec);  
};

let dynamic = O();
dynamic.prop.creation = 'is interesting';
dynamic.prop.stuff.not.clear.what.this.could.be.used.for = 123;

// log out full structure
let f = (o) => {
  for (let i in o) {
    console.log(o[i]);
    if (typeof o[i] === 'object') f(o[i]);
  }
};
f(dynamic);

Outputs:

Proxy {creation: "is interesting", stuff: Proxy}
is interesting
Proxy {not: Proxy}
Proxy {clear: Proxy}
Proxy {what: Proxy}
Proxy {this: Proxy}
Proxy {could: Proxy}
Proxy {be: Proxy}
Proxy {used: Proxy}
Proxy {for: 123}
123

Leave a Reply

Your email address will not be published. Required fields are marked *