Last active
September 11, 2018 20:48
-
-
Save c7x43t/0539181fb77527251301298bf5a171a7 to your computer and use it in GitHub Desktop.
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
// This is implementing a iterable WeakMap | |
// It has the same methods as WeakMap and in addition: | |
// It's keys and values are readable properties. | |
// It can be iterated by map and reduce, Arguments: key, value | |
class IterableWeakMap{ | |
constructor(){ | |
Object.defineProperties(this,{ | |
keys:{ | |
enumerable: false, | |
writable: true, | |
value: [] | |
}, | |
values:{ | |
enumerable: false, | |
writable: true, | |
value: [] | |
}, | |
__Mapping__:{ | |
enumerable: false, | |
writable: false, | |
value: new WeakMap() | |
}, | |
length:{ | |
enumerable: false, | |
writable: true, | |
value: 0 | |
} | |
}); | |
} | |
set(key,value){ | |
const index=this.__Mapping__.get(key); | |
if(index===undefined){ | |
let newIndex; | |
// write | |
newIndex=this.keys.push(key)-1; | |
this.values.push(value); | |
this.__Mapping__.set(key,newIndex); | |
this.length++; | |
}else{ | |
// overwrite | |
this.values[index]=value; | |
} | |
} | |
get(key){ | |
const index=this.__Mapping__.get(key); | |
if(index!==undefined){ | |
return this.values[index]; | |
} | |
} | |
has(key){ | |
const index=this.__Mapping__.get(key); | |
return index!==undefined; | |
} | |
map(func){ | |
return this.keys.map((value,index)=>func(this.values[index],value)); | |
} | |
filter(func){ | |
return this.keys.filter((value,index)=>{ | |
return func(this.values[index],value); | |
}); | |
} | |
delete(key){ | |
const index=this.__Mapping__.get(key); | |
const iExists=index!==undefined; | |
if(iExists){ | |
delete this.keys[index]; | |
delete this.values[index]; | |
this.__Mapping__.delete(key); | |
this.length--; | |
} | |
return iExists; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment