Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

利用Object实现简易Map #20

Open
hstarorg opened this issue Jul 19, 2018 · 0 comments
Open

利用Object实现简易Map #20

hstarorg opened this issue Jul 19, 2018 · 0 comments

Comments

@hstarorg
Copy link
Owner

hstarorg commented Jul 19, 2018

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant