Skip to content

Instantly share code, notes, and snippets.

@betocantu93
Created March 10, 2021 21:37
Show Gist options
  • Save betocantu93/511fb380cc4f68883ac5fbc36a71775d to your computer and use it in GitHub Desktop.
Save betocantu93/511fb380cc4f68883ac5fbc36a71775d to your computer and use it in GitHub Desktop.
SuperHash PoC
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)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment