Search code examples
javascriptarraysdictionaryassociative

How to use a complex associative array in javascript?


I need this table http://code.google.com/apis/chart/docs/gallery/qr_codes.html#details in my program and I'm not even sure if an associative array is the way to go.

Given the type (numeric/alphanumeric), number of characters and EC (error correction) level, I want a function to return the version (first column).


Solution

  • First, JavaScript has "Arrays" and "Objects". By 'associative array' I assume you mean a JavaScript Object, using keys other than non-negative integers.

    You can create JavaScript object literals using syntax such as the following:

    var versions = {
      "1" : {
        rowcols : [21,21],
        charsByECLevel : {
          L : {
            digits:41,
            alpha:25
          },
          M : {
            digits:34,
            alpha:20
          }
        }
      },
      "2" : {
        rowcols : [25,25],
        charsByECLevel : {
          L : {
            digits:77,
            alpha:47
          },
          M : {
            digits:63,
            alpha:48
          }
        }
      }
    };
    

    You would then access the properties like so:

    console.log( versions[1].charsByECLevel.L.digits );
    // 41
    

    To loop through the values, you could do this:

    function findVersion( versions, level, digits ){
      for (var versionNumber in versions){
        if (versions.hasOwnProperty(versionNumber)){
          if (versions[versionNumber].charsByECLevel[level].digits == digits){
            return versionNumber;
          }
        }
      }
    }
    
    findVersion( versions, "L", 77 );
    // returns "2"
    

    Edit: Having written the above, if you only want to look up versions based on level and digits, you should probably reverse the hash. Instead of looping through and checking the versions, index them directly and look it up in constant time:

    var versionByLevelAndDigits = {
      L : {
         41 : 1,
         77 : 2,
        127 : 3
      },
      M : {
         34 : 1,
         63 : 2,
        101 : 3
      }
    };
    
    var version = versionByLevelAndDigits["L"][77];
    // 2