mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-26 10:26:29 +08:00
Use tricky method to resolve type check
This commit is contained in:
parent
5724719485
commit
305915270a
1 changed files with 10 additions and 9 deletions
|
@ -18,7 +18,7 @@ class Entry {
|
||||||
/* 基于数组简易实现的哈希表 */
|
/* 基于数组简易实现的哈希表 */
|
||||||
class ArrayHashMap {
|
class ArrayHashMap {
|
||||||
|
|
||||||
private readonly bucket: Entry | null[];
|
private readonly bucket: (Entry | null)[];
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
// 初始化一个长度为 100 的桶(数组)
|
// 初始化一个长度为 100 的桶(数组)
|
||||||
|
@ -52,8 +52,8 @@ class ArrayHashMap {
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 获取所有键值对 */
|
/* 获取所有键值对 */
|
||||||
public entries(): Entry[] {
|
public entries(): (Entry | null)[] {
|
||||||
let arr = [];
|
let arr: (Entry | null)[] = [];
|
||||||
for (let i = 0; i < this.bucket.length; i++) {
|
for (let i = 0; i < this.bucket.length; i++) {
|
||||||
if (this.bucket[i]) {
|
if (this.bucket[i]) {
|
||||||
arr.push(this.bucket[i]);
|
arr.push(this.bucket[i]);
|
||||||
|
@ -63,22 +63,22 @@ class ArrayHashMap {
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 获取所有键 */
|
/* 获取所有键 */
|
||||||
public keys(): number[] {
|
public keys(): (number | undefined)[] {
|
||||||
let arr = [];
|
let arr: (number | undefined)[] = [];
|
||||||
for (let i = 0; i < this.bucket.length; i++) {
|
for (let i = 0; i < this.bucket.length; i++) {
|
||||||
if (this.bucket[i]) {
|
if (this.bucket[i]) {
|
||||||
arr.push(this.bucket[i].key);
|
arr.push(this.bucket[i]?.key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return arr;
|
return arr;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 获取所有值 */
|
/* 获取所有值 */
|
||||||
public values(): string[] {
|
public values(): (string | undefined)[] {
|
||||||
let arr = [];
|
let arr: (string | undefined)[] = [];
|
||||||
for (let i = 0; i < this.bucket.length; i++) {
|
for (let i = 0; i < this.bucket.length; i++) {
|
||||||
if (this.bucket[i]) {
|
if (this.bucket[i]) {
|
||||||
arr.push(this.bucket[i].val);
|
arr.push(this.bucket[i]?.val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return arr;
|
return arr;
|
||||||
|
@ -121,6 +121,7 @@ map.print();
|
||||||
/* 遍历哈希表 */
|
/* 遍历哈希表 */
|
||||||
console.info('\n遍历键值对 Key->Value');
|
console.info('\n遍历键值对 Key->Value');
|
||||||
for (const entry of map.entries()) {
|
for (const entry of map.entries()) {
|
||||||
|
if (!entry) continue;
|
||||||
console.info(entry.key + ' -> ' + entry.val);
|
console.info(entry.key + ' -> ' + entry.val);
|
||||||
}
|
}
|
||||||
console.info('\n单独遍历键 Key');
|
console.info('\n单独遍历键 Key');
|
||||||
|
|
Loading…
Reference in a new issue