I am learning javascript and my coaches have suggested me to refactor this code, I really don't know how I can do it, I would like you to guide me or show me examples of how to do it or how it could be by applying a refactoring.
In this function what I do is create a new object from an existing one, extracting data and using it to feed the new created object.
I can only use vanilla JS
console.time("total")
const computeDataTwo = (datos) => {
const mapAthletes = new Map();
for (let j = 0; j < datos.length; j++) {
const element = datos[j];
if (!mapAthletes.has(element.name)) {
const initValueAthletes = {
gold: 0,
bronze: 0,
silver: 0,
total: 0
}
mapAthletes.set(element.name + " " + element.team, initValueAthletes)
}
}
for (let j = 0; j < datos.length; j++) {
const element = datos[j];
const athletes = mapAthletes.get(element.name + " " + element.team);
if (element.medal === "Gold") {
athletes.gold = athletes.gold + 1;
}
if (element.medal === "Bronze") {
athletes.bronze = athletes.bronze + 1;
}
if (element.medal === "Silver") {
athletes.silver = athletes.silver + 1;
}
athletes.total = athletes.total + 1;
mapAthletes.set(element.name + " " + element.team, athletes)
}
const arrayAthletes = [];
mapAthletes.forEach((value, key) => {
const totalMedalByAthletes = {
name: key,
gold: value.gold,
silver: value.silver,
bronce: value.bronze,
total: value.total
};
arrayAthletes.push(totalMedalByAthletes);
})
return arrayAthletes
}
let datos = [{name:"pepe", team:"equipo1", medal: "Gold"},{name:"juan", team:"equipo2"}]
console.log(computeDataTwo(datos))
console.timeEnd("total")
Here I leave you a small refactoring of the code, I understand that it does everything the same that you were doing, let me know if it is useful to you.
And here I leave you another one with even less laps.
And another one, further reducing the code.
And since I'm a handle, here I leave you another one.
And the last one but it already gets very difficult to read and has no performance advantages.
there I leave you an option that occurred to me greetings!