Skip to content

Commit e5c24d2

Browse files
committed
⚡️ enumにメゾット機能作成
1 parent 636e510 commit e5c24d2

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

dynamicEnum.js

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,22 @@ class _EnumItem {
66
* @param {string} name - Enumのキー名
77
* @param {number} ordinal - 順序番号(自動インクリメント)
88
* @param {any} value - 任意の値(name, 数値, オブジェクトなど)
9+
* @param {_DynamicEnumCore} [owner] - Enumのインスタンス
10+
* @param {{[methodName: string]: (...args: any[]) => any}} [methods] - Enumのメソッド
911
*/
10-
constructor(name, ordinal, value = name) {
12+
constructor(name, ordinal, value = name, owner = null, methods = {}) {
1113
this.name = name;
1214
this.ordinal = ordinal;
1315
this.value = value;
1416

17+
this.owner = owner;
18+
19+
for (const [key, fn] of Object.entries(methods)) {
20+
if (typeof fn === "function") {
21+
this[key] = fn.bind(this);
22+
}
23+
}
24+
1525
Object.freeze(this);
1626
}
1727

@@ -64,10 +74,12 @@ class _EnumItem {
6474
class _DynamicEnumCore {
6575
/**
6676
* @param {Array<string | [string, any]> | Record<string, any>} defs - 定義
77+
* @param {{[methodName: string]: (...args: any[]) => any}} [options.methods] - Enumのメソッド
6778
*/
68-
constructor(defs) {
79+
constructor(defs, options = {}) {
6980
/** @type {_EnumItem[]} */
7081
this._items = [];
82+
this._methods = options.methods || {};
7183

7284
let entries;
7385

@@ -80,7 +92,7 @@ class _DynamicEnumCore {
8092
}
8193

8294
entries.forEach(([name, value], index) => {
83-
const item = new _EnumItem(name, index, value);
95+
const item = new _EnumItem(name, index, value, this, this._methods);
8496
Object.defineProperty(this, name, {
8597
value: item,
8698
writable: false,
@@ -200,10 +212,11 @@ class _DynamicEnumCore {
200212
/**
201213
* DynamicEnum生成関数(インデックスアクセスに対応したProxy付き)
202214
* @param {Array<string | [string, any]> | Record<string, any>} defs
215+
* @param {{[methodName: string]: (...args: any[]) => any}} [options.methods] - Enumのメソッド
203216
* @returns {_DynamicEnumCore & Proxy}
204217
*/
205-
function DynamicEnum(defs) {
206-
const core = new _DynamicEnumCore(defs);
218+
function DynamicEnum(defs, options = {}) {
219+
const core = new _DynamicEnumCore(defs, options);
207220
return new Proxy(core, {
208221
get(target, prop, receiver) {
209222
if (typeof prop === "string" && /^[0-9]+$/.test(prop)) {

0 commit comments

Comments
 (0)