Last active
April 24, 2018 04:07
-
-
Save CreeJee/855dd861b29d8ec84490f7d86848db33 to your computer and use it in GitHub Desktop.
weakMap + Enum (maybe it will not useful)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const WeakEnumSymbol = Symbol("__Types"); | |
class WeakEnum{ | |
static symbol(){ | |
return WeakEnumSymbol; | |
} | |
static __primitiveToObj__(obj) { | |
if (obj instanceof Object) { | |
return obj; | |
} | |
else if(obj === undefined || obj === null || typeof obj === "symbol"){ | |
throw new Error(`not convertable for [value : ${obj} ,type: ${typeof obj}]`) | |
} | |
else{ | |
return new obj.constructor(obj); | |
} | |
}; | |
get handler(){ | |
const __instance = this; | |
return { | |
get : function(target,name,receiver) { | |
for(let key of target.keys){ | |
if(key.valueOf().toString() === name){ | |
return target[WeakEnumSymbol].get(key); | |
} | |
}; | |
return undefined; | |
} | |
} | |
} | |
constructor(...enums){ | |
this.length = 0; | |
this.keys = []; | |
this[WeakEnumSymbol] = new WeakMap(); | |
enums.map((element, index) => { | |
let __element = WeakEnum.__primitiveToObj__(element); | |
let __index = WeakEnum.__primitiveToObj__(index); | |
this.keys.push(__element,__index); | |
if(isNaN(parseInt(element))){ | |
if(this[WeakEnumSymbol].has(__element)){ | |
throw new Error(`Duplicate identifier at ${element}`); | |
} | |
else{ | |
this[WeakEnumSymbol].set(__element,index).set(__index,element); | |
this[index] = element; | |
this.length++; | |
} | |
} | |
else{ | |
throw new Error('An enum member cannot have a numeric name.') | |
} | |
}) | |
return new Proxy(this,this.handler); | |
} | |
} | |
enumObj = new WeakEnum("a","b","c"); | |
console.log(enumObj[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment