Node.js - Multimap

1k views Asked by At

I have the following data(example) -

1 - "Value1A" 1 - "Value1B" 1 - "Value1C" 2 - "Value2A" 2 - "Value2B"

I'm using Multimaps for the above data, such that the key 1, has 3 values(Value1A, Value1B, Value1C) and key 2 has 2 values(Value2A, Value2B).

When I try to retrieve all the values for a given key using the get function, it works. But I want to get the key given the value. i.e. if I have "Value1C", I want to use this to get its key 1, from the Multimap. Is this possible, if so how and if not what other than Multimap can I use to achieve this result.

Thanks for the help

https://www.npmjs.com/package/multimap

1

There are 1 answers

0
fmodos On BEST ANSWER

It is not possible to do this with a single operation, You will need to choose beetween use some extra memory or consume CPU resource.

  1. Use more memory

In this case you need to store the data in a reverse mapping. So you will have another map to store as "Value1C" -> 1. This solution can cause consistency issues, since all the operations will need to be updated in both map. The original one and the reverse one. The example for this code is basic:

//insert
map.set(1, "Value1C");
reverseMap.set("Value1C", 1);

//search
console.log(map.get(reverseMap.get("Value1C")));
  1. Use more CPU

In this cause you will need to do a search throught all the values, this will be an O(n) complexity. It is not good if your list is too big, even worst in a single thread environment like Node.js. Check the code example below:

function findValueInMultiMap(map, value, callback){
    map.forEachEntry(function (entry, key) {
       for(var e in entry){
          if(entry[e]==value){
             callback(map.get(key));
          }
       }  
    });
}

findValueInMultiMao(map, 'Value1C', function(values){
   console.log(values); 
});