Skip to content

Instantly share code, notes, and snippets.

@deepakshrma
Last active May 10, 2020 09:05
Show Gist options
  • Select an option

  • Save deepakshrma/ffac5daf91cba20dfd4f6f1733cdc913 to your computer and use it in GitHub Desktop.

Select an option

Save deepakshrma/ffac5daf91cba20dfd4f6f1733cdc913 to your computer and use it in GitHub Desktop.
Basic implementation of Enum of typescript in vanila javascript.
class Enum {
constructor(args, startIndex = 0, defaultValue) {
const em = args.split("|").reduce((m, key, index) => {
m[(m[key] = index + startIndex)] = key;
return m;
}, {});
em.value = em.key = (k) => em[k];
return new Proxy(em, {
get: (obj, prop) => (prop in obj ? obj[prop] : defaultValue),
set: (obj, prop, value) => {
if (prop in obj) {
throw new Error("cant set same value again"); // // cant set same value again
}
em[(em[prop] = value)] = prop;
},
});
}
}
const DOWNLOAD_STATES = new Enum("START|INPROGRESS|FINISHED", 1);
console.log(JSON.stringify(DOWNLOAD_STATES));
// {"1":"START","2":"INPROGRESS","3":"FINISHED","START":1,"INPROGRESS":2,"FINISHED":3}
const { START } = DOWNLOAD_STATES;
console.log(`CURR STATE is ${START}`);
// CURR STATE is 1
console.log(`CURR STATE is ${DOWNLOAD_STATES[2]}`);
// CURR STATE is INPROGRESS
// ADD new State:
DOWNLOAD_STATES.IDLE = 4;
console.log(`CURR STATE is ${DOWNLOAD_STATES[4]}`);
// CURR STATE is IDLE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment