JavaScript数据结构与算法——字典Dictionary

字典

创建一个字典

function Dictionary() {
    var items = {};
    this.has = function(value) {
        return value in items;
    };

    this.set = function(key, value) {
        items[key] = value;
    };

    this.remove = function(key) {
        if (this.has(key)) {
            delete items[key];
            return true;
        }
        return false;
    };

    this.get = function(key) {
        return this.has(key) ? items[key] : undefined;
    };

    this.values = function() {
        var values = [];
        for(var k in items) {
            // if (items.hasOwnProperty(k)) values.push(items[k]);
            if (this.has(k)) values.push(items[k]);
        }
        return values;
    };

    this.clear = function() {
        items = {};
    };

    this.size = function() {
        var count = 0;
        for (var k in items) {
            if (items.hasOwnProperty(k)) ++count;
        }
        return count;
    };

    this.keys = function() {
        var keys = [];
        for(var key in items) keys.push(key);
        return keys;
    };
}

哈希表

function HashTable() {
    var table = [];

    // 私有方法,给定一个key参数,我们就能根据组成key的每个字符的
    // ASCII码值的和得到一个数字
    var loseloseHashCode = function(key) {
        var hash = 0;
        for (var i = 0; i < key.length; i++) {
            hash += key.charCodeAt(i);  // 从ASCII表中查到
            //的每个字符对应的ASCII值加到hash变量中
        }
        return hash % 37;  // 为了得到比较小的数值
    };

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

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

    this.remove = function(key) {
        table[loseloseHashCode(key)] = undefined;
    };
}

猜你喜欢

转载自blog.csdn.net/phoebe_16/article/details/80775966