Skip to content

Instantly share code, notes, and snippets.

@betocantu93
Created March 10, 2021 21:37
Show Gist options
  • Select an option

  • Save betocantu93/511fb380cc4f68883ac5fbc36a71775d to your computer and use it in GitHub Desktop.

Select an option

Save betocantu93/511fb380cc4f68883ac5fbc36a71775d to your computer and use it in GitHub Desktop.

Revisions

  1. betocantu93 created this gist Mar 10, 2021.
    55 changes: 55 additions & 0 deletions superhash.js
    Original 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)
    }
    }
    }