Write yourself a JavaScript map class

Source: Internet
Author: User
Tags map class

The weeks, JS is not a map class, want to use also have to encapsulate one of their own.

The code is as follows Copy Code

(function (Win) {
var Map = function () {
This.count = 0;
This.entryset = {};
};

var proto = Map.prototype;

Proto.size = function () {
return this.count;
};

Proto.isempty = function () {
return this.count = = 0;
};

Proto.containskey = function (key) {
if (This.isempty ()) {
return false;
}

For (Var prop in This.entryset) {
if (prop = = key) {
return true;
}
}

return false;
};

Proto.containsvalue = function (value) {
if (This.isempty ()) {
return false;
}

for (var key in This.entryset) {
if (this.entryset[key] = = value) {
return true;
}
}

return false;
};

Proto.get = function (key) {
if (This.isempty ()) {
return null;
}

if (This.containskey (key)) {
return This.entryset[key];
}

return null;
};

Proto.put = function (key, value) {
This.entryset[key] = value;
this.count++;
};

Proto.remove = function (key) {
if (This.containskey (key)) {
Delete This.entryset[key];
this.count--;
}
};

Proto.putall = function (map) {
for (var key in Map.entryset) {
This.put (Key, Map.entryset[key]);
}
};

Proto.clear = function () {
for (var key in This.entryset) {
This.remove (key);
}
};

Proto.values = function () {
var result = [];

for (var key in This.entryset) {
Result.push (This.entryset[key]);
}

return result;
};

Proto.keyset = function () {
var result = [];

for (var key in This.entryset) {
Result.push (key);
}

return result;
};

proto.tostring = function () {
var result = [];
for (var key in This.entryset) {
Result.push (key + ":" + This.entryset[key]);
}

Return "{" + result.join () + "}";
};

proto.valueof = function () {
return this.tostring ();
};

    win. Map = map;
}) (window);

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.