Created
March 10, 2021 21:37
-
-
Save betocantu93/511fb380cc4f68883ac5fbc36a71775d to your computer and use it in GitHub Desktop.
Revisions
-
betocantu93 created this gist
Mar 10, 2021 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,55 @@ function set(target, name, value) { const attrConfig = target.constructor?.attributes[name]; if (typeof attrConfig?.init === 'function') { target[name] = attrConfig.init.call(this, value); } if (attrConfig?.defaultValue) { target[name] = attrConfig.defaultValue; } else if (typeof attrConfig?.transform === 'function') { target[name] = attrConfig.transform.call(target, value); } else { target[name] = value; } return true; } class SuperHash { static attributes = {}; static initialize(proxy, props) { Object.keys(props).forEach((prop) => { proxy[prop] = props[prop]; }); } constructor(props) { const proxy = new Proxy(this, { set, get(target, name) { return target[name] } }); SuperHash.initialize(proxy, props); return proxy; } } class FirstName extends SuperHash { static attributes = { value: { transform: (value) => value.toUpperCase() } } } class LastName extends SuperHash { static attributes = { value: { transform: (value) => value.toLowerCase() } } } class Name extends SuperHash { static attributes = { firstName: { transform: (val) => new FirstName(val) }, lastName: { transform: (val) => new LastName(val) } } }