JavaScript 의 유사배열을 이용한 List,Map 구조 구현
JavaScipt 의 유사배열을 이용하여 자료구조의 List,Map의 역할을 하는 객체를 만들어보았다.
List 는 기본 구현인 add,get을 Map 은 기본 구현인 put,get 을 구현하였다.
============ Map 구조 구현============
function Map() {
this.elements = {};
this.length = 0;
}
Map.prototype.put = function(key,value) {
this.length++;
this.elements[key] = value;
}
Map.prototype.get = function(key) {
return this.elements[key];
}
var map = new Map();
map.put("name","이상훈");
console.log(map.get("name"));
console.log(map.length);
============ List 구조 구현============
function List() {
this.elements = {};
this.idx = 0;
this.length = 0;
}
List.prototype.add = function(element) {
this.length++;
this.elements[this.idx++] = element;
};
List.prototype.get = function(idx) {
return this.elements[idx];
};
var list = new List();
list.add("이상훈");
list.add("자바스크립트 신동");
console.log(list.get(0));
console.log(list.get(1));
console.log(list.length);