The example has been picked from
operationsdashboard/src/Demo/Flight/Preflightdata.js
In order to write better code, we should always think about readiblity of code and nameing conventions. Readibility of code make it easy for new developer to adopt the code and make new changes. For example you can see t5, t4, convertTime2, etc in the code. Any new developer can not understant the code directly, he/she must have to read the entire code and understand it's uses.
useEffect(() => {
let t1 =
preflightData &&
preflightData.map((d) => {
return d.order_No;
});
if (t1 && t1.length >= 15) t1.splice(0, t1.length - 15);
setLabels(t1);
let t2 =
preflightData &&
preflightData.map((d) => {
return d.time && d.time.prep ? convertTime2(d.time.prep) : 0;
});
if (t2 && t2.length >= 15) t2.splice(0, t2.length - 15);
setPrepTime(t2);
let t3 =
preflightData &&
preflightData.map((d) => {
return d.time && d.time.takeOff ? convertTime2(d.time.takeOff) : 0;
});
if (t3 && t3.length >= 15) t3.splice(0, t3.length - 15);
setTakeOffTime(t3);
let t4 =
preflightData &&
preflightData.map((d) =>
d.time && d.time.takeOff && d.time.prep
? (new Date(d.time.takeOff).getTime() -
new Date(d.time.prep).getTime()) /
1000 /
60
: 0
);
let t5 = [];
t4 &&
t5.push(Math.max(...t4).toFixed(2)) &&
t5.push(Math.min(...t4).toFixed(2));
t4 && t5.push(t4.reduce((sum, val) => sum + val / t4.length, 0).toFixed(2));
setTimeData(t5);
}, [preflightData, ecoOrders]);
useEffect(() => {
GET(`operations/pre-flight-graph-time?orgId=${orgId}&ecoId=${ecoId}`)
.then(res => {
setLabels(res.data.map(flightData => flightData.order_No));
setPrepTime(res.data.map(flightData => convertTime2((flightData?.time?.prep) || 0)));
setTakeOffTime(res.data.map(flightData => convertTime2((flightData?.time?.takeOff) || 0)));
let timeData = res.data.map((flightData)=>{
if (!flightData.time || !flightData.time.takeOff || !flightData.time.prep)
return 0;
return (new Date(flightData.time.takeOff).getTime() - new Date(flightData.time.prep).getTime())/1000/60;
})
const maxMinAvgTime = [];
maxMinAvgTime.push(Math.max(...timeData).toFixed(2)); // maximum time
maxMinAvgTime.push(Math.min(...timeData).toFixed(2)); // minimum time
maxMinAvgTime.push(timeData.reduce((sum, val) => sum + val / timeData.length, 0).toFixed(2)); // average time
setTimeData(maxMinAvgTime)
})
.catch(err => console.log(err));
}, []); // do not add dependency until it's really required
- Code length
The old code consist of 45 lines whereas new code consist of 23 lines with clear understanding of what we ae doing.
- Changes
t4 -> timeData
t5 -> maxMinAvgTime
` Requires
No one can uderstand what does mean by convertTime2
, it should be either convertTime
or convertTimeToSomething
.
Now, you can see with better code we have achived the reduced LOC(lines of code) and betetr readibility.
Also,
and
are extra lines if we save the data above as previous example.