Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created October 18, 2022 11:23
Show Gist options
  • Save semlinker/4544e53aac22f5914e43c69c186339e2 to your computer and use it in GitHub Desktop.
Save semlinker/4544e53aac22f5914e43c69c186339e2 to your computer and use it in GitHub Desktop.
Proxy API usage scenarios —— Builder API
function Builder(typeOrTemplate, template) {
let type;
if (typeOrTemplate instanceof Function) {
type = typeOrTemplate;
} else {
template = typeOrTemplate;
}
const built = template ? Object.assign({}, template) : {};
const builder = new Proxy(
{},
{
get(target, prop) {
if ("build" === prop) {
if (type) {
// A class name (identified by the constructor) was passed. Instantiate it with props.
const obj = new type();
return () => Object.assign(obj, Object.assign({}, built));
} else {
// No type information - just return the object.
return () => built;
}
}
return (...args) => {
// If no arguments passed return current value.
if (0 === args.length) {
return built[prop.toString()];
}
built[prop.toString()] = args[0];
return builder;
};
},
}
);
return builder;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment