JSFiddle - React, Tailwind, and code Playground
by kkdaily
HTML
<p>
assume you have a location service that tells you all the sub-regions that comprise the input region.
For ex: if you give the input as "Earth", it will return a list of all continents in the world ["North America", "Europe", ...] Or if you put in United States, it would return all the states.
Given 2 regions, write a method that returns the smallest region of both inputs. For ex, "California" and "Mexico" should return "North America" and "San Francisco" and "Virginia" should return "United States"
</p>
JavaScript
/**
- start by making a request to the location service with input "Earth" to get an array of strings back of continents
- iterate through the array of continents and check if either of the provided regions are present in the list
- if at least 1 of the regions are in the list, then the most recent input given to the location service should be output as the smallest shared region
- if neither regions are on the list, then iterate through the current list of regions and make a call to the location service with each individual region
- check if either region is present like above
- if not, then increment counter by 1, store the outputs into a new array of subregions, and make another request to the location service with the next region name
- repeat the above steps recursively until 1 of the regions is found, or until neither is found in which case return a "not found" message
**/
const LOCATION_SERVICE_URL = '<some_url>'
const region1 = '<some_region>'
const region2 = '<some_region>'
const findSmallestSharedRegion = async (region1, region2) => {
let region1LowerCase = region1.toLowerCase()
let region2LowerCase = region2.toLowerCase()
if (region1LowerCase === 'earth' || region2LowerCase === 'earth') {
return 'Earth'
}
let currentRegionToSearch = 'Earth'
let matchingRegionFound = false
while (!matchingRegionFound) {
let subregions = await getSubRegions(currentRegionToSearch)
if (subregions.find(region1) || subregions.find(region2)) {
matchingRegionFound = true
} else {
}
}
return
}
const getSubRegions = (region) => {
return fetch(LOCATION_SERVICE_URL, {
region: currentRegionToSearch
})
.then((result) => {
return result.json()
})
}