Created
October 18, 2022 11:23
-
-
Save semlinker/4544e53aac22f5914e43c69c186339e2 to your computer and use it in GitHub Desktop.
Proxy API usage scenarios —— Builder API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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