JSFiddle - React, Tailwind, and code Playground

by Csaba Hellinger

JavaScript

function makeEnum(values) {
    const keys = Object.keys(values);
    const forEach = fn => Object.keys(values).forEach(fn);
    const handler = {
        set (obj, prop, value) {
            throw new TypeError('Enum is read only');
        },
        get (obj, prop) {
            if (prop === 'forEach') {
            	return forEach;
            }
            
            if (!(prop in obj)) {
                throw new ReferenceError(`Unknown enum key "${prop}"`);
            }
            return Reflect.get(obj, prop);
        },
        deleteProperty (obj, prop) {
            throw new TypeError('Enum is read only');
        }
    };
    return new Proxy(values, handler);
}

const values = {  ONE: 1,   TWO: 2};
const MyEnum = makeEnum(values);

values.THREE = 333;



MyEnum.forEach(key => console.log(key));
//console.log(Object.keys(MyEnum));