Map class implementation for JS simulation

  • 2021-06-28 11:22:15
  • OfStack

An example of Map class for JS simulation is given in this paper.Share it for your reference, as follows:

Implement key - value save according to map attribute in java

1. Store data using arrays, (use closures)


function Map() {
  var struct = function (key, value) {
    this.key = key;
    this.value = value;
  }
  var put = function (key, value) {
    for (var i = 0; i < this.arr.length; i++) {
      if (this.arr[i].key === key) {
        this.arr[i].value = value;
        return;
      }
    }
    this.arr[this.arr.length] = new struct(key, value);
  }
  var get = function (key) {
    for (var i = 0; i < this.arr.length; i++) {
      if (this.arr[i].key === key) {
        return this.arr[i].value;
      }
    }
    return null;
  }
  var remove = function (key) {
    var v;
    for (var i = 0; i < this.arr.length; i++) {
      v = this.arr.pop();
      if (v.key === key) {
        continue;
      }
      this.arr.unshift(v);
    }
  }
  var size = function () {
    return this.arr.length;
  }
  var isEmpty = function () {
    return this.arr.length <= 0;
  }
  this.arr = new Array();
  this.get = get;
  this.put = put;
  this.remove = remove;
  this.size = size;
  this.isEmpty = isEmpty;
}

2. Store data using JSON (extend method using prototype)


function Map() {
  this.obj = {};
  this.count = 0;
}
Map.prototype.put = function (key, value) {
  var oldValue = this.obj[key];
  if (oldValue == undefined) {
    this.count++;
  }
  this.obj[key] = value;
}
Map.prototype.get = function (key) {
  return this.obj[key];
}
Map.prototype.remove = function (key) {
  var oldValue = this.obj[key];
  if (oldValue != undefined) {
    this.count--;
    delete this.obj[key];
  }
}
Map.prototype.size = function () {
  return this.count;
}
var map = new Map();
map.put("key","map");
map.put("key","map1");
alert(map.get("key"));//map1
map.remove("key");
alert(map.get("key"));//undefined

More readers interested in JavaScript-related content can view this site's topics: Summary of JavaScript Switching Effects and Techniques, Summary of JavaScript Finding Algorithmic Techniques, Summary of JavaScript Animation Effects and Techniques, Summary of JavaScript Errors and Debugging Techniques, Summary of JavaScript Data Structure and Algorithmic Techniques.Summary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Operation Usage

I hope that the description in this paper will be helpful to everyone's JavaScript program design.


Related articles: