I'm doing some refactoring of someone else's code, and just want a second opinion, because of course I think my work makes it better, but some validation (or correction) would be helpful.
Starting with an array like this:
errorLog: [{
errorCode: 11,
errorDescription: "abc",
date: "2017-01-01",
severity: "H"
},{
errorCode: 11,
errorDescription: "abcd",
date: "2017-01-02",
severity: "H"
},{
errorCode: 99,
errorDescription: "abcd",
date: "2017-01-02",
severity: "H"
}]
and trying to get results like this:
errorSummary: [{
errorCode: 11,
severity: "H",
count: 2
},{
errorCode: 99,
severity: "H",
count: 1
}]
this is the existing code:
//instead of this, which is hard to reason about and debug (and includes a line that will never rturn true: if (hardErrorsSorted.includes...)):
let hardErrors = testData.filter(ts1 => ts1.severity === 'H');
let hardErrorsSorted = hardErrors.sort(this.mySorter);
for (let i = 0; i < hardErrorsSorted.length; i++) {
if (i != hardErrorsSorted.length - 1) {
if (hardErrorsSorted[i].errorCode != hardErrorsSorted[i + 1].errorCode) {
let errorCount = this.getCount(hardErrorsSorted, hardErrorsSorted[i].errorCode);
this.errorDataList.push({
errorCode: hardErrorsSorted[i].errorCode,
errorCodeType: 'H',
errorCodeTotalCount: errorCount
});
}
} else {
if (hardErrorsSorted.includes(hardErrorsSorted[i].errorCode, 0)) {
} else {
let errorCount = this.getCount(hardErrorsSorted, hardErrorsSorted[i].errorCode);
this.errorDataList.push({
errorCode: hardErrorsSorted[i].errorCode,
errorCodeType: 'H',
errorCodeTotalCount: errorCount
});
}
}
}
and my refactoring:
//use something like this, which is much easier to grasp at a glance, doesn't jump around, and is DRYer
let hardErrorCodes = testData.filter(ts => ts.severity === 'H').map(v => v.errorCode);
let hardErrorCounts = {};
//sum up the unique errors
for (let error of hardErrorCodes) {
if (!(error in hardErrorCounts)) {
hardErrorCounts[error] = 0;
}
hardErrorCounts[error]++;
}
//add the summed error counts to the master list
for (let error in hardErrorCounts) {
this.errorDataList.push({
errorCode: error,
errorCodeType: "H",
errorCodeTotalCount: hardErrorCounts[error]
});
What do you all think? Is this a helpful refactor, or a waste of time?