2015년 9월 5일 토요일

Javascript Map, Set

Let's see Javascript Map and Set. We'll see Javascript specific things and something is good to know. Learning test is written using Jasmine. Please refer Jasmine usage which I wrote before if you have interest it. 

1. map basic
You can iterate elements of map using for-of  statement. As see in [line 11], You can access the element using [key, value] form. The equality of key is evaluate both type and value using identity operator "===".

it("map basic", function() {
var map = new Map();
map.set("name", "thinkhard.j.park");
map.set("sex", "male");
expect(map.has("name")).toBe(true);
expect(map.get("name")).toBe("thinkhard.j.park");
expect(map.size).toBe(2);
for (var kv of map) {
console.log("key, value : " + kv[0] + ", " + kv[1]);
}
map.delete("sex");
expect(map.has("sex")).toBe(false);
map = new Map();
map.set(1, "Number 1");
map.set("1", "String 1");
for (var kv of map) {
console.log("equality is works like the identity comparison operator === : " + kv[0] + "," + kv[1]);
}
});
2. object vs map
Let's compare object and map. The attribute(key) of object should be defined using string, but map can use any type as a key. We can know the size of map using size method, but object need to iterate to calculate its size manually.

it ("object vs map", function() {
var object = { "key" : "only striing type is possible as a key"};
expect(object.size).toBe(undefined);
var size = 0;
for (var key in object) {
size++;
}
expect(size).toBe(1);
});
3. set basic
As you can see in [line 16], the key of map is also evaluate both type and value using identity operator "===".

it("set basic", function() {
var set = new Set();
set.add(1);
set.add("hi");
set.add("hello");
expect(set.has(1)).toBe(true);
set.delete("hi");
expect(set.size).toBe(2);
set = new Set();
set.add("1");
set.add(1);
for (var v of set) {
console.log("equality is works like the identity comparison operator === : " + typeof v + ", " + v);
}
expect(set.size).toBe(2);
});
4. array and set
As see in [line 5] , When convert array to set, duplicated element are removed except one.

it("array and set", function() {
var aray = [1,2,3,3,4];
var mySet = new Set(aray);
expect(mySet.size).toBe(4);
for (var v of mySet) {
console.log(v);
}
});
5. Reference
- MDN - https://developer.mozilla.org/en/docs/Web/JavaScript
- Jasmine - http://jasmine.github.io/2.3/introduction.html

댓글 없음:

댓글 쓰기