Pre-release
AdventureJS Docs Downloads
Score: 0 Moves: 0
//validateAssetList.js
/*global adventurejs A*/

/**
 * Serialize asset names in an array. Asset names may be nested
 * inside objects in the array. A secondary effect of this function
 * is that it converts object properties from strings to arrays,
 * which corrects for cases of authors providing strings for
 * properties that want arrays. For example: "skeleton key"
 * would be converted to ["skeleton_key"].
 * @method adventurejs#validateAssetList
 * @memberOf adventurejs
 * @param {String|Array} property
 * @returns {Array}
 */
adventurejs.validateAssetList = function Adventurejs_validateAssetList(
  property
) {
  if ("undefined" === typeof property) return [];
  if ("string" === typeof property) {
    property = A.stringToArray(property);
  }

  if (Array.isArray(property)) {
    for (var i = 0; i < property.length; i++) {
      // ex: [ "id" ]
      if ("string" === typeof property[i]) {
        property[i] = A.serialize(property[i]);
      }

      // ex: [ {"id":['preposition']} ]
      else if (Object(property[i]) === property[i]) {
        for (var key in property[i]) {
          var value = property[i][key];
          var id = A.serialize(key);
          if ("string" === typeof value) {
            value = A.stringToArray(A.serialize(value));
          }
          if (Array.isArray(value) || Object(value) === value) {
            value = A.validateAssetList(value);
          }
          delete property[i][key];
          property[i][id] = value;
        }
      }
    }
  }

  // ex: [ {"id":['preposition']} ]
  else if (Object(property) === property) {
    for (var key in property) {
      var value = property[key];
      var id = A.serialize(key);
      if ("string" === typeof value) {
        value = A.stringToArray(A.serialize(value));
      } else if (Array.isArray(value) || Object(value) === value) {
        value = A.validateAssetList(value);
      }
      delete property[key];
      property[id] = value;
    }
  }

  return property;
};