[removed] using tuples as dictionary keys

前端 未结 4 1958
-上瘾入骨i
-上瘾入骨i 2021-02-06 23:21

I have a situation where I want to create a mapping from a tuple to an integer. In python, I would simply use a tuple (a,b) as the key to a dictionary,

Does

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 23:34

    You could use my jshashtable and then use any object as a key, though assuming your tuples are arrays of integers I think your best bet is one you've mentioned yourself: use the join() method of Array to create property names of a regular object. You could wrap this very simply:

    function TupleDictionary() {
     this.dict = {};
    }
    
    TupleDictionary.prototype = {
     tupleToString: function(tuple) {
      return tuple.join(",");
     },
    
     put: function(tuple, val) {
      this.dict[ this.tupleToString(tuple) ] = val;
     },
    
     get: function(tuple) {
      return this.dict[ this.tupleToString(tuple) ];
     }
    };
    
    var dict = new TupleDictionary();
    dict.put( [1,2], "banana" );
    alert( dict.get( [1,2] ) );
    

提交回复
热议问题