美文网首页
11 【HashMap】js Hashmap

11 【HashMap】js Hashmap

作者: 狩秋之人 | 来源:发表于2019-11-16 23:57 被阅读0次

要考试了,每天打卡变少,考完继续加油!

'use strict';

class HashMap {
    constructor () {
        this.table = []
    }
    // 散列函数
    loseloseHashCode (key) {
        let hash = 0;
        for(let i = 0; i < key.length; i++) {
            hash += key[i].charCodeAt()
        }
        return hash % 37
    }

    put (key, value) {
        let position = this.loseloseHashCode(key)
        console.log(position + '-' + key);
        this.table[position] = value 
    }

    remove (key) {
        this.table[this.loseloseHashCode(key)] = undefined
        return 'ok!'
    }

    get (key) {
        return this.table[this.loseloseHashCode(key)]
    }
}

let hashmap = new HashMap();
console.log('TEST1: put()');
hashmap.put('one', 1)
console.log('TEST2: get()');
console.log(hashmap.get('one'));
console.log('TEST3: remove()');
console.log(hashmap.remove('one'));
console.log(hashmap.get('one'));


相关文章

网友评论

      本文标题:11 【HashMap】js Hashmap

      本文链接:https://www.haomeiwen.com/subject/rkiuictx.html