I am using a 3rd party API that allows me to search for housing properties. Unfortunately the API is not written in a way to allow me to search for a range so I have to make a separate call for each value in the range.
So if I want to search for all the housing properties that have 2 or 3 bedrooms I would have to make call for 2 bedrooms, then another call for 3 bedrooms. Now this can get quite tricky as there are multiple fields that can contain a range of numbers (bedrooms, bathroom, floors, garage size...).
My brute force JavaScript solution for this is to create a nested for loop that will create an array of all the calls. This is not a scalable solution and I'm looking for a way to dynamically create this for loop or another alternative way to get an array of all my calls.
My current solution:
const searchParams = {
minBedrooms: 2,
maxBedrooms: 4,
minBathrooms: 1,
maxBathrooms: 3,
minFloors: 1,
maxFloors: 1
};
let promises = [];
for (let bedrooms = searchParams.minBedrooms; bedrooms <= searchParams.maxBedrooms; bedrooms++) {
for (let bathrooms = searchParams.minBathrooms; bathrooms <= searchParams.maxBathrooms; bathrooms++) {
for (let floors = searchParams.minFloors; floors <= searchParams.maxFloors; floors++) {
promises.push(callApi(bedrooms, bathrooms, floors));
}
}
}
Promise.all(promises).then(response => {
// do stuff with response
}
Furthermore the user might not specify one of the search parameters (ie - number of bedrooms). As a result, the API will not apply that specific filter. My code currently will fail no bedroom values are passed in, and writing condition statements for each for loop is not a desire of mine.
Any ideas on how to dynamically generate the above nested for loop?
EDIT
My current solution will fail if the user does not specify the number of bedrooms but specifies bathrooms/floors as the initial for loop will not get run. I don't want to resort to using condition statements along with lots of nested loops to be creating my promise array. This is why I feel like I need to use a dynamically generated for loop.
Promise.all(promises).then(response => ...);. I will update my code with this.[](Array), not{}(Object).