dictionary implementation in typescript

Dictionary implementation in TypeScript

As a C# developer, Dictionary is very common and it’s a frequent part of development routine. it’s very helpful when we want to look up values based on keys. Just pass the keys and get the values…bingo. Moreover, C# library enables to use it as a generic way (using the same class with different data type – not dependant on specific data type).

Recently I started with typescript, typescript its superset of JavaScript. like C# typescript does not provide inbuilt support for Dictionary, if you want it you must implement it.

How to implement Dictionary in typescript?

In JavaScript, objects store various data as a key collection. Meaning every item in the object are stored as key-value pair.

Let’s understand this

let person = {
     name: "mahesh",   
     age: 28      
};

In the above example, we have created person object, it has two properties name, age.

These two properties will be stored as key-value pair. Where left-hand side value from the colon (:) is key after the colon (:) is a value. If you add person object to watch you will see below output.

Dictionary implementation in TypeScript

These property values can be accessible using the dot notation

person.name // mahesh
person.age// 28

JavaScript also provides support for adding or removing the properties from the object.

I hope now at least you got some clue how to proceed for Dictionary implementation.

Dictionary Interface

Like C# we need basic options to add, remove and get the value from a dictionary. So, I have created below interface which has some basic operations which our dictionary should provide.

export interface IDictionary<T> {
    AddItem(key: string, value: T);
    ContainsKey(key: string): boolean;
    Count(): number;
    Item(key: string): T;
    Keys(): string[];
    RemoveItem(key: string): T;
    Values(): T[];
}

Dictionary Implementation

Let’s implement all the members of the interface and use JavaScript object key-value pair feature to implement dictionary methods.

export class Dictionary<T> implements IDictionary<T> {
    private items: { [key: string]: T } = {};
    private count = 0;     

    AddItem(key: string, value: T) {        
      if (!this.items.hasOwnProperty(key)) {            
      	this.count++;
      }        
      this.items[key] = value;    
    }

  ContainsKey(key: string): boolean {        
  	return this.items.hasOwnProperty(key);    
  } 

  Count(): number {        
  	return this.count;    
  }

  Item(key: string): T {         
    return this.items[key];    
  }     

  Keys(): string[] {         
  const keySet: string[] = [];         
    for (const prop in this.items) {            
  		if (this.items.hasOwnProperty(prop)) {                
  			keySet.push(prop);            
  		}        
  	}         
  return keySet;    
  }     

  RemoveItem(key: string): T {       
  const val = this.items[key];       
  delete this.items[key];       
  this.count--;       
  return val;    
  }     

  Values(): T[] {
    const values: T[] = [];        
  	for (const prop in this.items) {            
  		if (this.items.hasOwnProperty(prop)) {
			values.push(this.items[prop]);            
  		}        
  	}        
  return values;    
  }
}

Usage of above implementation

let persons = new Dictionary<number>();
persons.Add('mahesh', 28);
persons.Add('saie', 1);
persons.Add('himanshu', 7);

persons.ContainsKey('sair'); // true
persons.ContainsKey('sudkisha'); // false
persons.Item('himanshu'); // 7
persons.Count(); // 3;

This above implementation fulfils my requirement. I hope this will help you too. we can also use array indexer to achieve dictionary implementation but I found this is the easy way out.


How to remove duplicate values from array in C#?

The Binary Numbering System (base-2)

Leave a Reply

Your email address will not be published. Required fields are marked *