딕셔너리
{}를 안쓰고 []로 만드는 이유가 뭘까. 그냥 이런게 있다는것에 집중하자.
Dictionary 클래스
function Dictionary(){
this.dataStore = new Array();
}
add()
함수는 키와 인자를 받는다 키는 값을 찾는데 사용되는 인덱스이다.
Dictionary.prototype.add = function(key,value){
this.dataStore[key] = value;
}
find()
함수를 정의한다. find()
함수는 키를 인자로 받아 키와 관련된 값을 반환한다.
Dictionary.prototype.find = function(){
return this.dataStore[key];
}
딕셔너리의 키와 값의 쌍을 지울때는 자바스크립트의 내장함수 delete()
를 사용한다. delete()
함수는 Object클래스의 일부며 인자로 키 레퍼런스를 받는다.
Dictionary.prototype.remove = function(key){
delete this.dataStore[key]
}
딕셔너리의 모든 키와 값을 확인할수 있는 showAll()
함수가 필요하다.
Dictionary.prototype.showAll = function(){
for(var key in this.dataStore){
console.log(key + ":" + this.dataStore[key]);
}
}
Dictionary 클래스의 부가 함수
Dictionary.prototype.count = function(){
var n = 0;
for(var key in this.dataStore){
n++;
}
return n;
}
count()
함수가 필요한 이유는 length프로퍼티는 문자열 키에서 작동하지 않기 때문이다.
var nums = new Array();
nums[0] = 0
nums[1] = 1
console.log(nums.length); // => 2
nums["a"] = "apple";
nums["b"] = "banana";
console.log(nums.length); // => 2 ?!
nums.count(); // => 4 !! 숫자 인덱스도 포함한다.
모든 항목을 삭제하는 `clear()` 함수도 유용하다.
Dictionary.prototype.clear = function(){
for(var key in this.dataStore){
delete this.dataStore[key];
}
}
Dictionary 클래스에 정렬 기능 추가하기
키를 이용해 값을 얻는것이 딕셔너리의 핵심기능이다. 딕셔너리에 저장된 항목의 순서는 중요하지 않다. 하지만 딕셔너리의 항목을 정렬된 순서로 확인해야 할 때가 있다.
Dictionary.prototype.sort = function(){
var toSort = [],
sorted = [];
for(let key in this.dataStore){
toSort.push(key);
}
for(let item in toSort.sort()){
sorted[item] = this.dataStore[item]
}
return sorted;
}