gpt4 book ai didi

javascript - 这是对总结对象数组有益的 JavaScript 重构吗?

转载 作者:行者123 更新时间:2023-12-01 02:47:04 25 4
gpt4 key购买 nike

这可能不是这里的典型问题,但我确实没有认识的人来检查这个问题。我正在对别人的代码进行一些重构,只是想听听第二个意见,因为我当然认为我的工作让它变得更好,但是来自你们专业人士的一些验证会很有帮助。 p>

从这样的数组开始:

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"
}]

并尝试获得这样的结果:

errorSummary: [{
errorCode: 11,
severity: "H",
count: 2
},{
errorCode: 99,
severity: "H",
count: 1
}]

这是现有代码:

//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
});
}
}
}

以及我的重构:

//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]
});

大家觉得怎么样?一个有用的重构?还是浪费时间?

最佳答案

你甚至可以更进一步:

const result = [], ids = {};

for(const {errorCode, severity} of hardErrorCodes){
if(severity !== "H") continue;
if(ids[errorCode]){
ids[errorCode].count++;
}else{
result.push( ids[errorCode] = { severity, errorCode, count: 1});
}
}

这使其速度提高了 3 倍(理论上)

如果您不想过滤严重性:

for(const {errorCode, severity} of hardErrorCodes){
if(ids[severity + errorCode]){
ids[severity + errorCode].count++;
}else{
result.push( ids[severity + errorCode] = { severity, errorCode, count: 1});
}
}

关于javascript - 这是对总结对象数组有益的 JavaScript 重构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47184116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com