async function recommendRegion()

in index.js [265:335]


async function recommendRegion() {
  if(!regions) {
    if(!fetching) {
      await fetchData();
    } else {
      return;
    }
  }
  
  let params = {
    weights: {},
    locations: [],
  };

  // Add weights
  for (const input of inputs) {
    params.weights[input.name] = parseInt(input.value, 10) / 10;
  }

  // Add current location and any other selected country.
  const locationSelect = document.getElementById('locations')
  for (const option of locationSelect.options) {
    if (option.selected) {
      if (option.value === "--current-location--") {
        if (userCoords) {
          params.locations.push(userCoords);
        } else {
          console.log("Current location not available.");
        }
      } else {
        params.locations.push(JSON.parse(option.value));
      }
    }
  }

  // Array of allowed regions, based on selected products
  params.allowedRegions = new Set();
  // get currently selected products
  const productSelect = document.getElementById('products');
  if(productSelect.selectedIndex === -1) {
    console.warn("No selected product");
  } else {

    // Start with all regions in which the first selected product is available
    const firstSelectedOption = productSelect.selectedOptions[0];
    const firstSelectionRegionsMap = JSON.parse(firstSelectedOption.value);
    for (const region of Object.keys(firstSelectionRegionsMap)) {
      if(firstSelectionRegionsMap[region]) {
        params.allowedRegions.add(region);
      }
    }

    // For all other selected products, remove from the previous set any region where it's not available
    for (let o = 1; o < productSelect.selectedOptions.length; o++) {
      const regionsMap = JSON.parse(productSelect.selectedOptions[o].value);
      for (const region of Object.keys(regionsMap)) {
        if(!regionsMap[region]) {
          params.allowedRegions.delete(region);
        }
      }
    }
  }
  
  // TODO: Should we always store params in URL? or only when user hits 'Share'?
  // In any case, we need to handle the user coordinates in a special way:
  // First because it's an object that doesn't transforms well in JS.
  // Second, because we request location by default, so we probably don't want it to be captured in URL.
  // window.location.hash = encodeURIComponent(JSON.stringify(params));

  regionOptimizer(regions, params).then(printResults);
};