Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Last active April 30, 2021 19:46
Show Gist options
  • Select an option

  • Save GGrassiant/4bbdaac9f9e5f7c56d7a9072cd28adad to your computer and use it in GitHub Desktop.

Select an option

Save GGrassiant/4bbdaac9f9e5f7c56d7a9072cd28adad to your computer and use it in GitHub Desktop.
Reformat shitty api
const dataSet = [{
datetime: "January 3rd 1999 at 15:34 UTC",
location: 3,
animal: { isMammal: true, }
},
{
datetime: "January 3rd 1999 at 15:34 UTC",
location: 4,
animal: { isMammal: true, }
},
{
datetime: "January 3rd 1999 at 15:34 UTC",
location: 4,
animal: { isMammal: false, }
},
{
datetime: "January 4th 1999 at 15:34 UTC",
location: 4,
animal: { isMammal: false, }
},
{
datetime: "January 5th 1999 at 15:34 UTC",
location: 6,
animal: { isMammal: true, }
},
];
// TODO: Could be better with a Map()?
const mammalPercentages = (observations) => {
const formattedDataSet = observations.reduce((acc, cur) => {
const dateKey = cur.datetime.split('at')[0].trim(); // could use getUTCDate?
if (!acc[dateKey]) {
acc[dateKey] = {};
}
if (! acc[dateKey]["observations"]) {
acc[dateKey]["observations"] = [];
}
let obsForLoc = acc[dateKey]["observations"].find(el => el.location === cur.location);
if (!obsForLoc) {
acc[dateKey]["observations"].push({
location: cur.location,
animals: [],
})
}
obsForLoc = acc[dateKey]["observations"].find(el => el.location === cur.location);
obsForLoc["animals"].push(cur.animal);
return acc;
}, {});
const ratio = (arrayOfObservation) => {
const mamals = arrayOfObservation.filter((o) => o.isMammal);
return mamals.length / arrayOfObservation.length * 100;
}
return Object.entries(formattedDataSet).forEach((entry) => {
return entry[1].observations.forEach((obs) => {
console.log(
`On ${entry[0]}, for location ${obs.location}, ${ratio(obs.animals)}% of animals were mamals`
);
})
})
}
mammalPercentages(dataSet);
// prints:
// On January 3rd 1999, for location 3, 100% of animals were mamals
// On January 3rd 1999, for location 4, 50% of animals were mamals
// On January 4th 1999, for location 4, 0% of animals were mamals
// On January 5th 1999, for location 6, 100% of animals were mamals
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment