All files / engine/Source/Core queryToObject.js

100% Statements 22/22
100% Branches 10/10
100% Functions 1/1
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61                                                    336x 1x       335x 335x 42x   293x 293x 874x   874x 874x 874x 872x   2x     874x 874x   8x 866x 3x   863x     293x      
import defined from "./defined.js";
import DeveloperError from "./DeveloperError.js";
 
/**
 * Parses a query string into an object, where the keys and values of the object are the
 * name/value pairs from the query string, decoded. If a name appears multiple times,
 * the value in the object will be an array of values.
 * @function queryToObject
 *
 * @param {string} queryString The query string.
 * @returns {object} An object containing the parameters parsed from the query string.
 *
 *
 * @example
 * const obj = Cesium.queryToObject('key1=some%20value&key2=a%2Fb&key3=x&key3=y');
 * // obj will be:
 * // {
 * //   key1 : 'some value',
 * //   key2 : 'a/b',
 * //   key3 : ['x', 'y']
 * // }
 *
 * @see objectToQuery
 */
function queryToObject(queryString) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(queryString)) {
    throw new DeveloperError("queryString is required.");
  }
  //>>includeEnd('debug');
 
  const result = {};
  if (queryString === "") {
    return result;
  }
  const parts = queryString.replace(/\+/g, "%20").split(/[&;]/);
  for (let i = 0, len = parts.length; i < len; ++i) {
    const subparts = parts[i].split("=");
 
    const name = decodeURIComponent(subparts[0]);
    let value = subparts[1];
    if (defined(value)) {
      value = decodeURIComponent(value);
    } else {
      value = "";
    }
 
    const resultValue = result[name];
    if (typeof resultValue === "string") {
      // expand the single value to an array
      result[name] = [resultValue, value];
    } else if (Array.isArray(resultValue)) {
      resultValue.push(value);
    } else {
      result[name] = value;
    }
  }
  return result;
}
export default queryToObject;