Set and Dictionary
This lesson shows how to quickly access data without looping a list.
We'll cover the following
Storing information in a dictionary or a set is a great way to improve your performance when accessing data. In terms of “Big O” notation, dictionaries and sets are best at O(1)
meaning that the cost is constant regardless of how many items are stored.
Big O is a standard way to communicate the complexity of an algorithm. O(1) is the most efficient because it is constant regardless of how many elements you are manipulating.
TypeScript has a couple of ways in which you can achieve this quick access.
Index signatures
There have already been a couple of lessons concerning index signature, thus, I will not reiterate the details. Nevertheless, the simplest way to have a dictionary is by mapping an object as a key to each property as a value.
In the example below, line 4 defines the index signature. Lines 8-9 set values to the dictionary. The key to access the value is defined between the square brackets. In that case, the keys are 1
and 10
. Accessing the value on line 11 is very quick because there is no traversing of a list or complex algorithm involved.
Get hands-on with 1200+ tech skills courses.