实现es6中的set和map

转载自: https://www.cnblogs.com/hui-fly/p/9459152.html

https://blog.csdn.net/roamingcode/article/details/81975913

set

function Set (arr) {
  let item = {};
  this.size = 0;
  if (arr) {
    for (let i of arr) {
      item[i] = i;
    }
    this.size = arr.length;
  }

  this.has = function (val) {
    return item.hasOwnProperty(val);
  }
  this.add = function (val) {
    if (!this.has(val)) {
      item[val] = val;
      this.size ++;
    }
  }
  this.delete = function (val) {
    if (this.has(val)) {
      delete item[val];
      this.size --;
    }
  }
  this.clear = function () {
    item = {};
    this.size = 0;
  }
  this.values = function () {
    return Object.values(item);
  }
}

let set = new Set([1, 2, 3]);
console.log(set.has(3));  // true
console.log(set.has(4));  // false
set.add(0);
console.log(set.has(0));  // true
console.log(set.size);    // 4
set.delete(3);
console.log(set.has(3));  // false
console.log(set.size);   // 3
console.log(set.values());  // [0,1,2]

 

map

class Map {
  constructor (arr = []) {
    this.items = {};
    this.size = 0;
    arr.forEach(arr_item => {
      this.set(arr_item[0], arr_item[1]);
    })
  }
  has (val) {
    return this.items.hasOwnProperty(val);
  }
  set (key, val) {
    if (!this.has(key)) {
      this.size ++;
    }
    this.items[key] = val;
  }
  get (key) {
    return this.has(key)? this.items[key]: undefined;
  }
  delete (key) {
    if (this.items.has(key)) {
      delete this.items[key];
      this.size --;
      return true;
    } else {
      return false;
    }
  }
  clear () {
    this.items = {};
    this.size = 0;
  }
  keys () {
    return Object.keys(this.items);
  }
  values () {
    return Object.values(this.items);
  }
}

let map = new Map([['name', 'alice'], ['age', 19]]);
console.log(map.has('age'));  // true
console.log(map.get('age'));  // 19
map.set('address', 'bupt');
map.set('age', 20);
console.log(map.size); // 3 console.log(map.keys());
// [ 'name', 'age', 'address' ] console.log(map.values()); // [ 'alice', 20, 'bupt' ]

 

posted @ 2019-09-20 22:01  cecelia  阅读(220)  评论(0编辑  收藏  举报