//因为每个键和每个键值对都设置为字符串类型,这样方便检索,所以需要写一个函数用来进行字符串转换
function defaultToString(item){
if(item == 'null'){
return 'null';
}
if(item == 'undefined'){
return 'undefined';
}
if(typeof item || item instanceof String){
return `${item}`;
}
return item.toString();
}
//新建一个键值对的类
class valuePair{
constructor(key, value){
this.key = key;
this.value = value;
}
toString(){
return `[#${this.key}:${this.value}]`;
}
}
//新建一个字典类
class Dictionary{
constructor(toStrFn = defaultToString){
this.toStrFn = toStrFn;
this.table = {};
}
//判断键是否存在的方法
hasKey(key){
return this.table[this.toStrFn(key)] != null;
}
//给字典添加键和键对应的键值对的方法
set(key,value){
const tableKey = this.toStrFn(key);
this.table[tableKey] = new valuePair(key,value);
}
//根据键来获取键对应的值的方法
get(key){
const valuePair = this.table[this.toStrFn(key)];
return valuePair== null?undefined:valuePair.value;
}
//获取当前字典的长度的方法
size(){
return Object.keys(this.table).length;
}
//判断当前字典是否为空
isEmpty(){
return this.size() == 0;
}
//获取当前字典的所有键值对
keyValues(){
let valuePair = [];
for(let k in this.table){
valuePair.push(this.table[this.toStrFn(k)]);
}
return valuePair;
}
//获取当前字典的所有键
keys(){
return this.keyValues().map(valuePair => valuePair.key);
}
//获取当前字典的所有值
values(){
return this.keyValues().map(valuePair => valuePair.value);
}
//遍历当前字典的键值对
forEach(callBackFn){
let valuePairs = this.keyValues();
for(let i = 0; i < valuePairs.length; i++){
const result = callBackFn(valuePairs[i].key,valuePairs[i].value);
if(result == false){
break;
}
}
}
//将键值对以字符串形式打印出来
toString(){
if(this.isEmpty()){
return '';
}
let objString = `${this.keyValues()[0].toString()}`;
let valuePairs = this.keyValues();
for(let i = 1; i < this.size(); i++){
objString = `${objString},${valuePairs[i].toString()}`//调用valuePair类中的toString方法
}
return objString;
}
remove(key){
if(this.hasKey(key)){
delete this.table[this.toStrFn(key)];
return true;
}
return false;
}
}