DEV Community

Cover image for Hash Tables? How to avoid IF/Switch in JS
juanpumpkinpie
juanpumpkinpie

Posted on

Hash Tables? How to avoid IF/Switch in JS

Easily they are associative data structures that allow you to create list paired values, retrieving from the key.

Why to use them?
Because is more fast to: space, search, insertion and delete operations. Javascript Object is the sample of hash tables.

let Obj = {
Juan: "developer",
Shellby: "recruiter"
}
Enter fullscreen mode Exit fullscreen mode

Javascript has implemented a way to approach the hash tables using map to store the data.

const newCollection = new Map();
newCollection.set("Juan", "developer"); // Paired
newCollection.set("Marina", "developer");
newCollection.set("Shellby", "recruiter"); // Paired

console.log(newCollection.get("Juan")); // -> Developer
console.log(newCollection.size); // -> 3
Enter fullscreen mode Exit fullscreen mode

So, as you can see above, Map use get and set to pair the Object. But as difference using Map you can't overwrite their values because it violates the inherited method property hasOwnProperty().

How to IMPLEMENT a Hash Table Data Structure in Javascript?
Let's make an exercise with Marvel Comic characters vs. Characters. Implement a logic to define who wins a fight between 'Loki' character assuming who's attacking:

attack Loki must be:
Iron-Man Magneto
Thor Odin
Hulk Thanos
Wolwerine Magneto

Here is the answer. Usually you could follow this pattern generated by:

const attack = "Iron-Man";
const Loki = "";

if(attack === 'Iron-Man'){
 loki = 'Magneto'; //-> Loki custom as Magneto;
}else if(attack === 'Hulk'){
 loki = 'Thanos';  //-> Loki custom as Thanos;
}..etc..
else{
loki='loki';
}

Enter fullscreen mode Exit fullscreen mode

In this point, many developers can to think about refactor to switch because it works as:

switch(attack){
   case 'Iron-Man':
   loki = 'Magneto'
   break;

   default:
   Loki = 'Loki'

(.. so on)...
}

Enter fullscreen mode Exit fullscreen mode

Implementation HashTable:
You could use attack as index for the hash table to recover the value and refactor as clean code below:

const attack = 'Hulk'
Enter fullscreen mode Exit fullscreen mode
const LOKI_CUSTOM = {

'Iron-Man': 'Magneto',
 Thor: 'Odin',
 Hulk: 'Thanos',
}
Enter fullscreen mode Exit fullscreen mode
const LOKI_DEFAULT = 'Loki'
const loki = LOKI_CUSTOM[attack] || LOKI_DEFAULT

console.log(loki) -> Thanos

Enter fullscreen mode Exit fullscreen mode

It also allow you to export and re-use the object, and it can be implemented with methods and ternary functions! e.x:

const LOKI_CUSTOM = {

'Iron-Man': () => 'Magneto',
 Thor: () => 'Odin',
 Hulk: () => 'Thanos',
}
Enter fullscreen mode Exit fullscreen mode
const loki = LOKI_CUSTOM[attack]
 ? LOKI_CUSTOM[attacks]()
 : LOKI_DEFAULT
Enter fullscreen mode Exit fullscreen mode

Top comments (0)