@Dev-MV6
Posted
Hi there 👋, good job on completing the challenge.
I came across your solution and decided to write a function to give you an idea of how you can achieve what you want to do with the ideal weight ranges. First of all, I think you definitely have to find a better way to store the weight ranges in your data.json
, here's one way you can do it:
{
"100": { "min": 13.9, "max": 21.9 },
"110": { "min": 14.3, "max": 23.3 },
"120": { "min": 15.0, "max": 24.8 },
"130": { "min": 15.7, "max": 26.2 },
"140": { "min": 16.5, "max": 27.7 },
"150": { "min": 17.4, "max": 29.2 },
"160": { "min": 18.5, "max": 31.0 },
"170": { "min": 19.6, "max": 32.8 },
"180": { "min": 20.8, "max": 34.7 },
"190": { "min": 22.1, "max": 36.6 },
"200": { "min": 23.5, "max": 38.6 },
"210": { "min": 24.9, "max": 40.7 },
"220": { "min": 26.5, "max": 42.9 },
"230": { "min": 28.1, "max": 45.3 },
"240": { "min": 29.9, "max": 47.7 },
"250": "out of range"
}
And here's the function to fetch and consume the data:
let idealWeights
function getIdealWeight(userHeight) {
if (!idealWeights) {
// Fetch data
fetch("data.json")
.then((response) => {
if (!response.ok) throw new Error("Unable to get ideal weight: And error occured while fetching the data")
return response.json()
})
.then((data) => {
idealWeights = data
getIdealWeight(userHeight)
})
} else {
// Use fetched data
const heightRangeKey = Object.keys(idealWeights) // Get all keys from object
.sort((a, b) => parseInt(b) - parseInt(a)) // Sort heights
.find((height) => parseInt(height) <= userHeight) // Find matching height
const idealWeightRange = idealWeights[heightRangeKey]
if (!idealWeightRange || idealWeightRange === "out of range") {
throw new Error("Unable to get ideal weight: Given height is out of range")
}
return idealWeightRange
}
}
console.log(getIdealWeight(180))
This is might not be the best solution for your problem but at least I hope it can give some hints for you to come up with something better. Good luck!
Hope you find this helpful 👍