英文:
Refactor this function to reduce its Cognitive Complexity
问题
尝试理解认知复杂性(Cognitive Complexity)
的以下示例。这更多关于将代码简化到其最简单的形式吗?
如何优化我的代码并使其更可读。条件是,如果数组对象具有属性"average",则显示一个带有平均列的表,否则不显示平均列。
英文:
Trying to understand Cognitive Complexity
with the following example. Is it more about reducing codes to its simplest form??
How do I optimize my code and make it more readable. The condition is if the array objects has a property "average", then display a table with average column else don't display the average column.
let columns: any[] = []
export const tableHeaders = (arr) => {
if (arr?.length > 0 && arr?.some(x => x.hasOwnProperty('average'))) {
if(arr?.some(x => x.average == "NA"))
{
columns = [
{
Header: 'MONTH',
accessor: 'date',
sortType: (a:any, b:any) => {
return (new Date(a.values.date).getTime() < new Date(b.values.date).getTime() ? -1 : 1)
}
},
{
Header: 'TOTAL',
accessor: 'total',
}
]
}
else{
columns = [
{
Header: 'MONTH',
accessor: 'date',
sortType: (a:any, b:any) => {
return (new Date(a.values.date).getTime() < new Date(b.values.date).getTime() ? -1 : 1)
}
},
{
Header: 'TOTAL',
accessor: 'total',
},
{
Header: 'AVERAGE',
accessor: 'average',
}
]
}
}
else
{
columns = [
{
Header: 'MONTH',
accessor: 'date',
sortType: (a:any, b:any) => {
return (new Date(a.values.date).getTime() < new Date(b.values.date).getTime() ? -1 : 1)
}
},
{
Header: 'TOTAL',
accessor: 'total',
}
]
}
return columns
}
答案1
得分: 3
你可以立即初始化columns
,因为前两个对象始终相同,不考虑if
表达式。
然后只需重复使用您最初的if
表达式,但多加一个条件来验证您的平均值是否有任何NA
值。
如果一切正常,您可以将第三个对象推入columns
数组中。如果不行,就返回columns
不变。
英文:
You can initiate columns
instantly, because the first 2 objects are always the same, regardless of the if
expression.
Then just re-use your initial if
expression but with 1 more condition to verify if your averages have any NA
value to it.
If everything checks out, you can push the 3rd object into the columns array. If not, just return columns as is.
let columns: any[] = []
export const tableHeaders = (arr) => {
columns = [
{
Header: 'MONTH',
accessor: 'date',
sortType: (a:any, b:any) => {
return (new Date(a.values.date).getTime() < new Date(b.values.date).getTime() ? -1 : 1)
},
{
Header: 'TOTAL',
accessor: 'total',
}];
// verify if it has averages and none of the averages have NA
if (arr?.length > 0 && arr?.some(x => x.hasOwnProperty('average') && x.average !== "NA")) {
columns.push({
Header: 'AVERAGE',
accessor: 'average',
});
}
return columns;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论