利用TS泛型机制仿一个ES6中的Map数据结构

38 阅读1分钟

回顾泛型特点

在使用函数方法和类还有类型别名,不需要为每个类型都编写一套代码,保证了代码的复用性和类型安全,需要注意的是它最终在编译之后是不存在的。

泛型应用

应用在函数中

在函数名称后添加 <T>

function User<T>(){
    //....
}

应用在类和别名中

class User<T>{
    //....
}
type User<T> = //....

使用泛型开发一个Map数据结构

interface MapItem<K,V>{
    key: K
    value: V
}

type CallBack<K,V> = (key:K,value:V) =>void

class MyMap<K,V>{
    private mapKeys: K[] = []
    private mapValues: V[] = []

    size(){
        return this.mapKeys.length
    }
    get(key:K){
        const index = this.mapKeys.findIndex((i) => i === key);
        return this.mapValues[index]
    }
    set(key:K,value:V){
        const index = this.mapKeys.findIndex((i) => i === key);
        if(index !== -1){
            this.mapValues.splice(index,1,value)
            return
        }
        this.mapKeys.push(key)
        this.mapValues.push(value)
    }
    delete(key:K){
        const index = this.mapKeys.findIndex((i) => i === key);
        this.mapKeys.splice(index,1)
        this.mapValues.splice(index,1)
    }
    forEach(CallBack:CallBack<K,V>){
        for(let i = 0; i < this.mapKeys.length;i++){
            const k = this.mapKeys[i]
            const v = this.mapValues[i]
            CallBack(k,v)
        }
    }
}