Skip to content

Instantly share code, notes, and snippets.

@licaomeng
Created September 14, 2017 15:24
Show Gist options
  • Save licaomeng/3f6741df5a237b3b9454b4c603a3b245 to your computer and use it in GitHub Desktop.
Save licaomeng/3f6741df5a237b3b9454b4c603a3b245 to your computer and use it in GitHub Desktop.
Map Utility for JavaScript
/**
* Created by lica on 6/12/2016.
*/
function Map() {
this.container = new Object();
}
Map.prototype.put = function (key, value) {
this.container[key] = value;
}
Map.prototype.get = function (key) {
return this.container[key];
}
Map.prototype.putAll = function (map) {
for (var key in map.container) {
if (key == 'extend') {
continue;
}
this.container[key] = map.container[key];
}
}
Map.prototype.entrySet = function () {
var set = new Array();
function Entry() {
this.entry = new Object();
}
Entry.prototype.getKey = function () {
for (var key in this.entry) {
if (key == 'extend') {
continue;
}
return key;
}
}
Entry.prototype.getValue = function () {
for (var key in this.entry) {
if (key == 'extend') {
continue;
}
return this.entry[key];
}
}
for (var key in this.container) {
var entry = new Entry();
if (key == 'extend') {
continue;
}
entry.entry[key] = this.container[key];
set.push(entry);
}
return set;
}
Map.prototype.keySet = function () {
var keySet = new Array();
var count = 0;
for (var key in this.container) {
// skip object's extend function
if (key == 'extend') {
continue;
}
keySet[count] = key;
count++;
}
return keySet;
}
Map.prototype.values = function () {
var values = new Array();
for (var key in this.container) {
if (key == 'extend') {
continue;
}
values.push(this.container[key]);
}
return values;
}
Map.prototype.isEmpty = function () {
var flag = true;
for (var key in this.container) {
if (key == 'extend') {
continue;
}
flag = false;
break;
}
return flag;
}
Map.prototype.size = function () {
var count = 0;
for (var key in this.container) {
// skip object's extend function
if (key == 'extend') {
continue;
}
count++;
}
return count;
}
Map.prototype.remove = function (key) {
delete this.container[key];
}
Map.prototype.clear = function () {
for (var key in this.container) {
if (key == 'extend') {
continue;
}
delete this.container[key];
}
}
Map.prototype.clone = function () {
var cloneObj = new Map();
cloneObj.putAll(this);
return cloneObj;
}
Map.prototype.toString = function () {
var str = "";
for (var i = 0, keys = this.keySet(), len = keys.length; i < len; i++) {
str = str + keys[i] + "=" + this.container[keys[i]] + ";\n";
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment