Arda Basoglu

Hashmap Data Structure in Javascript, Example with Node.js

  1. // Author: Arda Basoglu, ardabasoglu@gmail.com
  2. // This example demonstrates the use of map like (like hash map in Java and dictionary in C#) data structure
  3. // The code is tested with a machine Node.js installed
  4. // If you have Node.js installed on your machine run the script by writing "node map.example.js" on the console
  5.  
  6. // create a map
  7. var map = {};
  8.  
  9. // Add key, value pairs into the map with random strings
  10. for (var i = 0; i < 500; i++) {
  11.     var item =generateRandomString();
  12.     var value = generateRandomString();
  13.     map[item] = value;
  14. };
  15.  
  16. // Output every key, value pair onto the screen
  17. for (var i in map) {
  18.     console.log("Key: " + i + ", Value: " + map[i]);
  19. }
  20.  
  21. // The function required for generating random strings
  22. function generateRandomString()
  23. {
  24.     var randomString = "";
  25.     var randomStringSource = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  26.  
  27.     for( var i=0; i < 5; i++ ){
  28.         randomString += randomStringSource.charAt(Math.floor(Math.random() * randomStringSource.length));
  29.     }
  30.    
  31.     return randomString;
  32. }