SOURCE

// 散列表(又称哈希表)
// 哈希函数,输入任意长度的值,输出固定长度的值
// 通过哈希函数或散列函数将字典的key生成消息摘要(数字),
// 将value存储在数组中,下标为该消息摘要

// 哈希表的主要操作
// 1,散列函数
// 2,添加元素
// 3,获取元素
// 4,删除元素
// 5,是否为空
// 6,获取长度
// 7,清空散列

class HashTable{
    constructor(){
        this.table = []
    }
    // 1,散列函数
    loseloseHashCode(key){
        let hash = 0
        for(let i = 0; i < key.length; i++){
            hash += key.charCodeAt(i)
        }
        return hash % 37
    }
    // 2,添加元素
    put(key,value){
        let position = this.loseloseHashCode(key)
        console.log(`${position} - ${value}`)
        this.table[position] = value
    }
    // 3,获取元素
    get(key){
        return this.table[this.loseloseHashCode(key)]
    }
    // 4,删除元素
    remove(key){
        this.table[this.loseloseHashCode(key)] = undefined
    }
    // 5,是否为空
    isEmpty(){
        return this.size() === 0
    }
    // 6,获取长度
    size(){
        let count = 0
        this.table.forEach(val => {
            if(val !== undefined) count++
        })
        return count
    }
    // 7,清空散列
    clear(){
        this.table = []
    }
}

let hash = new HashTable();
hash.put('Gandalf', 'gandalf@email.com'); // 19 - Gandalf
hash.put('John', 'john@email.com'); // 29 - John
hash.put('Tyrion', 'tyrion@email.com'); // 16 - Tyrion

console.log(hash.isEmpty()); // false
console.log(hash.size()); // 3
console.log(hash.get('Gandalf')); // gandalf@email.com
console.log(hash.get('Loiane')); // undefined

hash.remove('Gandalf');
console.log(hash.get('Gandalf')); // undefined
hash.clear();
console.log(hash.size()); // 0
console.log(hash.isEmpty()); // true
console 命令行工具 X clear

                    
>
console