2016-07-05 50 views
1

我知道如何做到這一點(就簡單的實現而言),但我想要一種「最有效」和「最少量的代碼」(對於一個最小的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 

在此先感謝。

+0

哦,對於任何誤解對不起,我的意思是,我知道該怎麼做,在幼稚的做法,這可能不是短期和高效的條款。 – pokemon

回答

3

如果返回false,則可以使用對象作爲比較回調函數,並使用Array#every發生短路。

如果thisArg參數提供給every,它會被傳遞給callback調用時,用作其this值。否則,值undefined將被傳遞以用作其this值。 callback最終可觀察到的this值根據通常用於確定函數所見的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

+0

只是一個小問題,值'比較[符號] || compare ['> =']'對每次迭代都進行評估。 原因如果是這種情況,我們可以將它存儲在一個變量,使其更有效。 – pokemon

+0

它只是一次評估和內部訪問'this'。 –