@particle/make-enum
Advanced tools
Comparing version
# `@particle/make-enum` Changelog | ||
## v4.0.0 | ||
### Fixes & Updates | ||
* Support nested enums | ||
## v3.0.2 | ||
@@ -5,0 +10,0 @@ |
{ | ||
"name": "@particle/make-enum", | ||
"description": "A smart enum that throws when accessing a value that does not exist", | ||
"version": "3.0.2", | ||
"version": "4.0.0", | ||
"author": "Particle Industries, inc", | ||
@@ -38,3 +38,3 @@ "license": "UNLICENSED", | ||
}, | ||
"gitHead": "e8e05299134393ac129c13d96ad82ef33af21f33" | ||
"gitHead": "7930e3605dfef17cf2fb89f2f7239b8dfdcb42ba" | ||
} |
@@ -50,2 +50,6 @@ # `@particle/make-enum` | ||
// states.inprogress throws | ||
const nestedEnum = makeEnum(['animals.cow', 'animals.eagle']); | ||
// nestedEnum.animals.cow === 'animals.cow' | ||
// nestedEnum.animals.eagle === 'animals.eagle' | ||
``` | ||
@@ -52,0 +56,0 @@ |
@@ -18,18 +18,51 @@ /** | ||
* // states.inprogress throws | ||
* | ||
* const nestedEnum = makeEnum(['animals.cow', 'animals.eagle']); | ||
* // nestedEnum.animals.cow === 'animals.cow' | ||
* // nestedEnum.animals.eagle === 'animals.eagle' | ||
*/ | ||
module.exports = function makeEnum(values) { | ||
return new Proxy(values, { | ||
get: function makeEnumGet(target, prop) { | ||
const value = Reflect.get(...arguments); | ||
if (typeof value === 'undefined' && typeof prop === 'string' && prop !== 'prototype') { | ||
if (target.includes(prop)) { | ||
return prop; | ||
} else { | ||
throw new ReferenceError(`${prop} is not included in ${target.toString()}`); | ||
} | ||
// Build a nested object from dot-separated paths | ||
const nestedValues = values.reduce((obj, path) => { | ||
const parts = path.split('.'); | ||
let current = obj; | ||
for (let i = 0; i < parts.length; i++) { | ||
const part = parts[i]; | ||
if (i === parts.length - 1) { | ||
current[part] = path; // Assign the full path as the value | ||
} else { | ||
current[part] = current[part] || {}; // Create a nested object if necessary | ||
} | ||
return value; | ||
current = current[part]; | ||
} | ||
return obj; | ||
}, {}); | ||
// Convert the nested object to a flat array for index-based access | ||
const flatValues = values.map(value => value.split('.').reduce((acc, cur, idx, array) => { | ||
return idx === array.length - 1 ? acc + cur : acc + cur + '.'; | ||
}, '')); | ||
// Wrap the nestedValues in a proxy | ||
return new Proxy(nestedValues, { | ||
get: function (target, prop, receiver) { | ||
if (prop === Symbol.toStringTag) { | ||
return 'Enum'; | ||
} | ||
if (prop === 'length') { | ||
return flatValues.length; | ||
} | ||
if (!isNaN(prop)) { | ||
// Handle numeric indices | ||
return flatValues[prop]; | ||
} | ||
if (prop in target) { | ||
return Reflect.get(target, prop, receiver); | ||
} | ||
throw new ReferenceError(`${String(prop)} is not a valid enum value`); | ||
} | ||
}); | ||
}; | ||
5863
25.47%60
93.55%63
6.78%