字典(Dictionary)的javascript完成

原由

近来在看《数据结构与算法–javascript形貌》,然后上npmjs.org去搜刮,想找适宜的库参考并记录下来,以备今后用时能拿来即用,最没有发明很合本身意的,于是就决议本身逐一完成出来。

编程思绪

使用了裸对象datastore来举行元素存储;
完成了两种获得字典长度的要领,一种为变量跟踪,一种为及时盘算。

本身的完成

(function(){
    "use strict";

    function Dictionary(){
        this._size = 0;
        this.datastore = Object.create(null);
    }

    Dictionary.prototype.isEmpty = function(){
        return this._size === 0;
    };

    Dictionary.prototype.size = function(){
        return this._size;
    };

    Dictionary.prototype.clear = function(){
        for(var key in this.datastore){
            delete this.datastore[key];
        }
        this._size = 0;
    };

    Dictionary.prototype.add = function(key, value){
        this.datastore[key] = value;
        this._size++;
    };

    Dictionary.prototype.find = function(key){
        return this.datastore[key];
    };

    Dictionary.prototype.count = function(){
        var n = 0;
        for(var key in this.datastore){
            n++;
        }
        return n;
    };

    Dictionary.prototype.remove = function(key){
        delete this.datastore[key];
        this._size--;
    };

    Dictionary.prototype.showAll = function(){
        for(var key in this.datastore){
            console.log(key + "->" + this.datastore[key]);
        }
    };

    module.exports = Dictionary;
})();

源代码地点

https://github.com/zhoutk/js-data-struct
http://git.oschina.net/zhoutk/jsDataStructs
    原文作者:zhoutk
    原文地址: https://segmentfault.com/a/1190000003794214
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞