TypeScript hashmap/dictionary interface

前端 未结 3 1354
庸人自扰
庸人自扰 2021-01-31 06:48

I\'m new to using TypeScript and I\'m trying to implement a hashmap/dictionary interface. So far I have

export interface IHash {
    [details: string] : string;
         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 07:34

    var x : IHash = {};
    x['key1'] = 'value1';
    x['key2'] = 'value2';
    
    console.log(x['key1']);
    // outputs value1
    
    console.log(x['key2']);
    // outputs value2
    

    If you would like to then iterate through your dictionary, you can use.

    Object.keys(x).forEach((key) => {console.log(x[key])});
    

    Object.keys returns all the properties of an object, so it works nicely for returning all the values from dictionary styled objects.

    You also mentioned a hashmap in your question, the above definition is for a dictionary style interface. Therefore the keys will be unique, but the values will not.

    You could use it like a hashset by just assigning the same value to the key and its value.

    if you wanted the keys to be unique and with potentially different values, then you just have to check if the key exists on the object before adding to it.

    var valueToAdd = 'one';
    if(!x[valueToAdd])
       x[valueToAdd] = valueToAdd;
    

    or you could build your own class to act as a hashset of sorts.

    Class HashSet{
      private var keys: IHash = {};
      private var values: string[] = [];
    
      public Add(key: string){
        if(!keys[key]){
          values.push(key);
          keys[key] = key;
        }
      }
    
      public GetValues(){
        // slicing the array will return it by value so users cannot accidentally
        // start playing around with your array
        return values.slice();
      }
    }
    

提交回复
热议问题