【问题标题】:Checking if an array is sorted (increasing, strictly increasing, decreasing, strictly decreasing) in javascript most efficiently [closed]检查数组是否在javascript中最有效地排序(递增,严格递增,递减,严格递减)[关闭]
【发布时间】:2016-07-05 12:48:16
【问题描述】:

我知道怎么做(就简单的实现而言),但我想要一种“最有效”和“最少代码量”(对于最小的 js 库)没有任何其他依赖项的方法。

预期行为和细节(签名可选):

function isSorted(array, sign) {
    // code
}

console.log(isSorted([1,2,2,4]));
// true: default behaviour (non-decreasing or increasing; sign : '>=')

console.log(isSorted([4,3,2,1], '<'));
// true : strictly decreasing

console.log(isSorted([4,3,3,1], '<='));
// true : decreasing

提前致谢。

【问题讨论】:

  • 哦,很抱歉造成任何误解,我的意思是,我知道如何在幼稚的实现方面做到这一点,这可能不是那么简短和高效。

标签: javascript arrays performance sorting


【解决方案1】:

如果返回false,您可以使用对象进行比较回调和短路的Array#every

如果将thisArg 参数提供给every,则在调用时它将传递给callback,用作其this 值。否则,值undefined 将被传递用作其this 值。 this 最终可被 callback 观察到的值是根据确定函数看到的 this 的常用规则确定的。

function isSorted(array, sign) {
    var compare = {
        '<': function (a, b) { return a < b; },
        '>': function (a, b) { return a > b; },
        '<=': function (a, b) { return a <= b; },
        '>=': function (a, b) { return a >= b; },
    };
    return array.every(function (a, i, aa) {
        return !i || this(a, aa[i - 1]);
    }, compare[sign] || compare['>=']);
}

console.log(isSorted([1, 2, 2, 4]));           // true default behaviour (non-decreasing or increasing; sign : '>=')
console.log(isSorted([4, 3, 2, 1], '<'));      // true strictly decreasing
console.log(isSorted([4, 3, 3, 1], '<='));     // true decreasing
console.log(isSorted([1, 2, 42, 2, 4]));       // false
console.log(isSorted([4, 3, 42, 2, 1], '<'));  // false
console.log(isSorted([4, 3, 42, 3, 1], '<=')); // false

【讨论】:

  • 只是一个小问题,每次迭代都会评估compare[sign] || compare['&gt;=']的值吗?因为如果是这种情况,我们可以将其存储在一个变量中以提高效率。
  • 它只被评估过一次并在内部使用this访问。
猜你喜欢
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
相关资源
最近更新 更多