HstarDoc
HstarDoc copied to clipboard
利用Object实现简易Map
class Map {
constructor() {
this.$keyObj = {};
this.$valueObj = {};
this.$length = 0;
}
set(key, value) {
const autoKey = `key${Map.idx++}`;
this.$keyObj[autoKey] = key;
this.$valueObj[autoKey] = value;
// 需要判断是否覆盖来控制 $length
}
_getAutoKey(key) {
const keyItem = Object.entries(this.$keyObj).find(x => x[1] === key);
return keyItem[0];
}
get(key) {
const autoKey = this._getAutoKey(key);
if (!autoKey) {
return undefined;
}
return this.$valueObj[autoKey];
}
}
Map.idx = 1;
// Usage
var map = new Map();
var key = new Object();
map.set(key, 1);
console.log(map.get(key), map.get(key) === 1);