字典数据结构,由键值对组成。

class ValuePair {
    constructor(key, value) {
        this.key = key;
        this.value = value;
    }
}

class Dictionary {

    table = {}

    toString(item) {
        if (item === null) {
            return 'null';
        } else if (item === undefined) {
            return 'undefined';
        } else if (typeof item === 'string' || item instanceof String) {
            return item;
        }
        return JSON.stringify(item);
    }

    hasKey(key) {
        return this.table[this.toString(key)] != null;
    }

    set(key, value) {
        if (key != null && value != null) {
            const tablekey = this.toString(key);
            console.log(tablekey);
            this.table[tablekey] = new ValuePair(key, value);
            return true;
        }
        return false;
    }

    get(key) {
        const valuepair = this.table[this.toString(key)];
        return valuepair == null ? undefined : valuepair.value;
    }

    remove(key) {
        if (this.hasKey(key)) {
            delete this.table[this.toString(key)];
            return true;
        }
        return false;
    }

    keys() {
        return this.keyValues().map(item => item.key);
    }

    values() {
        return this.keyValues().map(item => item.value);
    }

    keyValues() {
        return Object.values(this.table);
    }

    size() {
        return Object.keys(this.table).length;
    }

    isEmpty() {
        this.size() === 0;
    }

    clear() {
        this.table = {};
    }

    forEach(callback) {
        const valuepair = this.keyValues();
        for (let i = 0; i < valuepair.length; i++) {
            callback(valuepair[i].key,valuepair[i].value);
        }
    }
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐