TypeScript - (七) TypeScript中泛型的使用以及一個迷你版Map

簡介:

     泛型是一種約定,可以約定類的類型以及類中屬性,方法返回值,參數等類型。

內容:

     根據編寫一個泛型Map瞭解泛型的作用和使用。

1.定義一個泛型的Node

// <>裏的K,和V就是我們定義的泛型,至於是什麼類型,我們也不知道。但是當創建之後,key和value對應的類型就會更改成定義的類型。
class Node<K,V>{
    key:K;
    value:V;
}

2.定義一個泛型的Map

export class Map<K,V> {
    
    // 聲明一個Node的泛型數組,Node的類型根據HashMap的類型變化
    private nodes:Node<K,V> [] = [];
    
    // 新增到nodes裏
    public put(key:K,value:V){
        let node:Node<K,V> = this.getNodeByKey(key);
        // null 就是當前數組裏沒有這個key的元素,反之就是有
        if(null == node){
            node = new Node<K, V>();
            node.key = key;
            node.value = value;
            this.nodes[this.nodes.length] = node;
        }else{
            // 當前nodes的value覆蓋
            this.nodes[this.nodes.indexOf(node)].value = value;
        }
    }
    
    // 查詢全部數據
    public queryAll(){
        return this.nodes;
    };
    
    // 根據key判斷是否包含元素
    public containKey(key:K): boolean{
        let node = this.getNodeByKey(key);
        if(null == node){
            return false;
        }
        return true;
    };
    
    // 根據value獲取key
    public getKey(value:V){
        let node = this.getNodeByValue(value);
        return node.key;
    }
    
    // 根據key獲取value
    public getValue(key:K){
        let node = this.getNodeByKey(key);
        return node.value;
    }
    
    // 根據key獲取node
    private getNodeByKey(key:K): Node<K,V>{
        let currentNodes = this.nodes;
        for (let i = 0; i < currentNodes.length; i++) {
            if(currentNodes[i].key == key){
                return currentNodes[i];
            }
        }
        return null;
    };
    
    // 根據value查詢node
    private getNodeByValue(value:V): Node<K,V>{
        let currentNodes = this.nodes;
        for (let i = 0; i < currentNodes.length; i++) {
            if(currentNodes[i].value == value){
                return currentNodes[i];
            }
        }
        return null;
    };
    
    // 根據key移除元素
    public remove(key:K){
        let node = this.getNodeByKey(key);
        if(null != node){
            this.nodes.splice(this.nodes.indexOf(node),1);
        }
    }
    
}

3. 測試下效果

import {Map} from "./Map";

// 定義了一個key是string,value是string的map
let map: Map<string,string> = new Map();
// 新增一個key = a ,value = ccc
map.put('a','ccc');
// 打印新增一個key = a  [ Node { key: 'a', value: 'ccc' } ]
console.log('新增一個key = a ', map.queryAll());

// 新增一個value不是string的試試
// Error:(11, 13) TS2345: Argument of type '1' is not assignable to parameter of type 'string'.
// 果然,value不是string的,直接提示錯誤了。
// map.put('a',1);
// 新增一個key不是string的試試
// Error:(15, 9) TS2345: Argument of type '1' is not assignable to parameter of type 'string'.
// 果然,key,直接提示錯誤了。
// map.put(1,'ss');

// 新增一個key = a ,value = bbbb
map.put('a','bbbb');
// 打印 新增一個key = a ,value = bbbb, 看看是不是覆蓋掉了:  [ Node { key: 'a', value: 'bbbb' } ]
console.log('新增一個key = a ,value = bbbb, 看看是不是覆蓋掉了: ', map.queryAll());

// 新增一個key = b ,value =bbbccb
map.put('b','bbbccb');
/*
* 打印:  新增一個key = b ,value =bbbccb:  [ Node { key: 'a', value: 'bbbb' },
        Node { key: 'b', value: 'bbbccb' } ]
* */
console.log('新增一個key = b ,value =bbbccb: ', map.queryAll());

// 是否包含key
// 是否包含key=a: true
console.log('是否包含key=a:', map.containKey('a'));
//  是否包含key=c: false
console.log('是否包含key=c:', map.containKey('c'));

// 移除key = a
map.remove('a');
// 移除一個存在的key = a之後: [ Node { key: 'b', value: 'bbbccb' } ]
console.log('移除一個存在的key = a之後:',map.queryAll());

// 嘗試移除一個不存在的key
map.remove('c');
//  嘗試移除一個不存在的key=c之後: [ Node { key: 'b', value: 'bbbccb' } ]
console.log('嘗試移除一個不存在的key=c之後:',map.queryAll());

 附:

    系列鏈接: https://blog.csdn.net/qq_36255237/article/category/9168635

    GitHub的Demo地址: https://github.com/chenrui123456/TypeScript-Demo

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章