使用闭包基于两个参数进行排序

时间:2018-09-29 20:16:34

标签: javascript

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

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

2 个答案:

答案 0 :(得分:3)

您可以使用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);

答案 1 :(得分:1)

通过迭代键及其返回值进行排序,您可以采用嵌套的闭合和短路方法。

这适用于任意数量的比较键。

const
    genCompareFn = (...keys) => (v => (a, b) => keys.some(k => v = (a[k] > b[k]) - (a[k] < b[k])) && v)(),
    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 }],
    compareFn1 = genCompareFn('s', 'b'),
    compareFn2 = genCompareFn('b', 'g');
    
console.log(scoreArray.sort(compareFn1));
console.log(scoreArray.sort(compareFn2));
.as-console-wrapper { max-height: 100% !important; top: 0; }