gpt4 book ai didi

javascript - 基于两个参数排序,使用闭包

转载 作者:行者123 更新时间:2023-11-29 17:41:56 24 4
gpt4 key购买 nike

我有一个对象列表。我想根据两个参数对其进行排序。我创建了一个排序函数,但我确信它可以重构。有什么建议么?

const scoreArray = [{
"code": "NOR",
"g": 11,
"s": 5,
"b": 10
},

{
"code": "RUS",
"g": 13,
"s": 11,
"b": 9
},
{
"code": "NED",
"g": 8,
"s": 7,
"b": 9
}
]

var getCompareFunction = (primaryKey, secondaryKey) => {
return ((primaryKey, secondaryKey) => {
return (x, y) => {
if (x[primaryKey] === y[primaryKey]) {
if (x[secondaryKey] > y[secondaryKey]) {
return -1
} else if (x[secondaryKey] < y[secondaryKey]) {
return 1
} else {
return 0
}
} else if (x[primaryKey] > y[primaryKey]) {
return -1
} else if (x[primaryKey] < y[primaryKey]) {
return 1
}
}

})(primaryKey, secondaryKey)
}



const compareFuncHolder = getCompareFunction('s', 'b')

scoreArray.sort(compareFuncHolder);

console.log(scoreArray);

最佳答案

您可以使用 partial application没有 IIFE .此外,您可以使用与初级的差异,如果结果为 0 使用 short-circuit evaluation 与次要的差异:

const scoreArray = [{"code":"NOR","g":11,"s":5,"b":10},{"code":"RUS","g":13,"s":11,"b":9},{"code":"NED","g":8,"s":7,"b":9}]

const getCompareFunction = (primaryKey, secondaryKey) => (x, y) =>
y[primaryKey] - x[primaryKey] || y[secondaryKey] - x[secondaryKey]

const compareFuncHolder = getCompareFunction('b', 's')

scoreArray.sort(compareFuncHolder);

console.log(scoreArray);

如果需要比较字符串值和数字,可以使用 < 或 >,并将比较结果转换为数字 (false -> 0, true -> 1) 使用 +/- 运算符(参见 bergi's comment ):

const scoreArray = [{"code":"NOR","g":11,"s":5,"b":10},{"code":"RUS","g":13,"s":11,"b":9},{"code":"NED","g":8,"s":7,"b":9}]

const compare = (x, y) => +(x > y) || -(y > x);

const getCompareFunction = (primaryKey, secondaryKey) => (x, y) =>
compare(y[primaryKey], x[primaryKey]) || compare(y[secondaryKey], x[secondaryKey])

const compareFuncHolder = getCompareFunction('code', 's')

scoreArray.sort(compareFuncHolder);

console.log(scoreArray);

关于javascript - 基于两个参数排序,使用闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572200/

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