js实现字典

字典

字典和集合很相似,集合以[值,值]的形式存储元素,字典则是以[键,值]的形式来存储元素

实现Dictionary

function defaultToString(item){
    // 将键转化为字符串
    if(item === null){
        return 'NULL'
    }else if(item === undefined){
        return 'UNDEFINED'
    }else{
        return item.toString()
    }

}

class valuePair{
   // 键值对 constructor(key, value){
this.key = key this.value = value } toString(){ return `[#${this.key}: ${this.value}]` } } class Dictionary{ constructor(toStrFn = defaultToString){ this.toStrFn = toStrFn // 键转化为字符串 this.table = {} } hasKey(key){ return this.table[this.toStrFn[key]] !== undefined } set(key, val){ // 添加新元素 if(key !== null && val !== null){ const strKey = this.toStrFn(key) this.table[strKey] = new valuePair(key, val) return true } return false } remove(key){ if (this.hasKey(key)) { delete this.table[this.toStrFn(key)] return true } return false } get(key){ const value = this.table[this.toStrFn(key)] return value === undefined ? null : value.value } keyValues(){ // 返回所有键值对组成的数组 // Object.values(obj): Returns an array of values of the enumerable properties of an object return Object.values(this.table) } keys(){ // 返回所有键组成的数组 return this.keyValues().map((val) => { return val.key }) } values(){ // 返回所有值组成的数组 return this.keyValues().map((val) => { return val.value }) } forEach(callbackFn){ // 传入一个函数,参数为(key, value),迭代数组中的每个键值对运行 const valuePair = this.keyValues() for(let i=0; i<valuePair.length; i++){ const result = callbackFn(valuePair[i].key, valuePair[i].value) if (result === false) { break // 出错立即停止 } } } size(){ return Object.keys(this.table).length } isEmpty(){ return this.size() === 0 } clear(){ this.table = {} } toString(){ if(this.isEmpty()){ return "" } const valuePairs = this.keyValues() let objString = `${valuePairs[0].toString()}` for(let i=1; i<this.size(); i++){ objString = `${objString},${valuePairs[i].toString()}` } return objString } }

 

posted @ 2021-08-10 22:52  邢韬  阅读(963)  评论(0编辑  收藏  举报