Pre-release
Adventure.js Docs Downloads
Score: 0 Moves: 0
// sortLookupValues.js

(function () {
  /*global adventurejs A*/
  "use strict";

  var p = adventurejs.Game.prototype;

  /**
   * Sort lookupTable values that contain multiple IDs.
   * @method adventurejs.Game#sortLookupValues
   * @memberOf adventurejs.Game
   */
  p.sortLookupValues = function Game_sortLookupValues() {
    // sort entries within table
    for (var prop in this.game.world_lookup) {
      var lookupValue = this.game.world_lookup[prop].IDs;

      /**
       * Lookup prop contains multiple values.
       * We need them sorted by longest to shortest word count.
       *
       * Ex:
       * world_lookup["brass_key"]: ["brass_key", "melted_brass_key", "broken_brass_key"]
       *
       *
       * During gameplay we run combineCompoundPhrases on user input,
       * so for example we're comparing "melted brass key" we don't want
       * to find "brass key" first which would leave "melted" orphaned.
       *
       */
      if (lookupValue.length > 1) {
        // sort it by word count from high to low
        var sortedLookupValues = [];

        // first get the longest word count
        var wordCount = 0;
        for (var i = 0; i < lookupValue.length; i++) {
          var length = lookupValue[i].split("_").length;
          if (length > wordCount) {
            wordCount = length;
          }
        }

        // now loop down from longest to shortest
        for (var w = wordCount; w > 0; w--) {
          // and check each item to see
          // if it matches current word count
          for (var i = 0; i < lookupValue.length; i++) {
            var length = lookupValue[i].split("_").length;

            if (length === w) {
              // if this item's word count matches current w
              // add this item to new sorted array
              sortedLookupValues.push(lookupValue[i]);
            }
          }
        }

        // write the sorted array back to the lookup table
        this.game.world_lookup[prop].IDs = sortedLookupValues;
      }
    }
  };
})();