1

how to reduce lines of code from this javascript

I have this code that the truth is repeated, it only changes the names since they do the same but the difference is that I send to call different data and I would like to reduce that code

const times = truck["Fase 1"];
const [h, m, s] = times.split(":");
const minutes = parseInt(h) * 60 + parseInt(m) + s / 60;
const time = minutes;
const color = time <= 18 ? "#0CC234" : time < 30 ? "#FACE5A" : "#FF0101";
const Fase2 = truck["Fase 2"];
console.log({ Fase2 });
const [hs, ms, ss] = Fase2.split(":");
const minutesF2 = parseInt(hs) * 60 + parseInt(ms) + ss / 60;
const time2 = minutesF2;
const colors = time2 <= 18 ? "#0CC234" : time2 < 30 ? "#FACE5A" : "#FF0101";

I feel that the code repeats itself a lot and that it can be reduced, but I don't know how

Submitted September 30th 2021 by Admin

Answers
0

You can move the repeated part to the function:

const truck = { 'Fase 1': '11:22:33', 'Fase 2': '11:22:33',
}; function getColor (fase) { const [h, m, s] = truck[fase].split(':'); const timeInMinutes = parseInt(h) * 60 + parseInt(m) + s / 60; const color = timeInMinutes <= 18 ? "#0CC234" : timeInMinutes < 30 ? "#FACE5A" : "#FF0101"; return color;
} console.log(getColor('Fase 1')); console.log(getColor('Fase 2'));

Admin | 2 weeks ago


0

There is a few unneeded variables.

const [h, m, s] = truck["Fase 1"].split(":");
const minutes = parseInt(h) * 60 + parseInt(m) + s / 60;
const color = minutes <= 18 ? "#0CC234" : minutes < 30 ? "#FACE5A" : "#FF0101"; const [hs, ms, ss] = truck["Fase 2"].split(":");
const minutesF2 = parseInt(hs) * 60 + parseInt(ms) + ss / 60;
const colors = minutesF2 <= 18 ? "#0CC234" : minutesF2 < 30 ? "#FACE5A" : "#FF0101";

Admin | 2 weeks ago



Relevant Questions