检查是否一个数组进行排序
示例
var sorted = require('is-sorted')
console.log(sorted([1, 2, 3]))
// => true
console.log(sorted([3, 1, 2]))
// => false
// supports custom comparators
console.log(sorted([3, 2, 1], function (a, b) { return b - a }))
// => true
代码
function defaultComparator (a, b) {
return a - b
}
module.exports = function checksort (array, comparator) {
if (!Array.isArray(array)) throw new TypeError('Expected Array, got ' + (typeof array))
comparator = comparator || defaultComparator
for (var i = 1, length = array.length; i < length; ++i) {
if (comparator(array[i - 1], array[i]) > 0) return false
}
return true
}
解析
- 此模块的核心只有一个
checksort
函数,接收两个参数,数组和自定义排序规则函数。- 其中数组是必填,如果不传会抛出
new TypeError('Expected Array, got ' + (typeof array))
异常,函数执行中断。 - 排序规则函数非必填,默认为从小到大的顺序排列。具体代码见最上面的
defaultComparator
函数。
- 其中数组是必填,如果不传会抛出
- 前期的赋值处理完成后,开始对数组每一项的值进行遍历。按照排序规则函数的约定,如果返回值为负数,则意味着不满足排序规则,最终返回false。
- 如果经过遍历后没有被
return false
,最终抛出return true
。