第五章、字典和散列表
字典由键值对组成
创建字典
// 字典元素
class ValuePair {
constructor(key, value) {
this.key = key;
this.value = value;
}
toString() {
return `[#${this.key}: ${this.value}]`;
}
}
// 字典
class Dictionary {
constructor() {
this.toStrFn = function(item) {
if (item === null) {
return "NULL";
} else if (item === undefined) {
return "UNDEFINED";
} else if (typeof item === "string" || item instanceof String) {
return `${item}`;
}
return item.toString();
};
this.table = {};
}
// 判断元素是否存在字典
hasKey(key) {
return this.table[this.toStrFn(key)] != null;
}
// 添加元素
set(key, value) {
if (key != null && value != null) {
const tableKey = this.toStrFn(key);
this.table[tableKey] = new ValuePair(key, value);
return true;
}
return false;
}
// 移除元素
remove(key) {
if (this.hasKey(key)) {
delete this.table[this.toStrFn(key)];
return true;
}
return false;
}
// 查找元素
get(key) {
if (this.hasKey(key)) {
return this.table[this.toStrFn(key)];
}
return undefined;
}
// 返回所有key value
keyValues() {
return Object.values(this.table);
}
// 返回所有key
keys() {
return this.keyValues().map(item => item.key);
}
// 返回所有value
values() {
return this.keyValues().map(item => item.value);
}
// 遍历字典
forEach(callBackFn) {
const valuePairs = this.keyValues();
for (let i = 0; i < valuePairs.length; i++) {
const result = callBackFn(valuePairs[i].key, valuePairs[i].value);
if (result === false) {
break;
}
}
}
// 字典大小
size() {
return Object.keys(this.table).length;
}
// 判断字典是否为空
isEmpty() {
return this.size() === 0;
}
// 清空字典
clear() {
this.table = {};
}
// 转为字符串输出
toString() {
if (this.isEmpty()) {
return "";
}
const valuePairs = this.keyValues();
let objString = `${valuePairs[0].toString()}`;
for (let i = 1; i < valuePairs.length; i++) {
objString = `${objString}, ${valuePairs[i].toString()}`;
}
return objString;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
构建散列表
散列表也叫 HashTable 类、 HashMap 类