检查是否一个数组进行排序

示例

  1. var sorted = require('is-sorted')
  2. console.log(sorted([1, 2, 3]))
  3. // => true
  4. console.log(sorted([3, 1, 2]))
  5. // => false
  6. // supports custom comparators
  7. console.log(sorted([3, 2, 1], function (a, b) { return b - a }))
  8. // => true

代码

  1. function defaultComparator (a, b) {
  2. return a - b
  3. }
  4. module.exports = function checksort (array, comparator) {
  5. if (!Array.isArray(array)) throw new TypeError('Expected Array, got ' + (typeof array))
  6. comparator = comparator || defaultComparator
  7. for (var i = 1, length = array.length; i < length; ++i) {
  8. if (comparator(array[i - 1], array[i]) > 0) return false
  9. }
  10. return true
  11. }

github仓库:https://github.com/dcousens/is-sorted

解析

  • 此模块的核心只有一个 checksort函数,接收两个参数,数组和自定义排序规则函数。
    • 其中数组是必填,如果不传会抛出 new TypeError('Expected Array, got ' + (typeof array)) 异常,函数执行中断。
    • 排序规则函数非必填,默认为从小到大的顺序排列。具体代码见最上面的 defaultComparator函数。
  • 前期的赋值处理完成后,开始对数组每一项的值进行遍历。按照排序规则函数的约定,如果返回值为负数,则意味着不满足排序规则,最终返回false。
  • 如果经过遍历后没有被 return false ,最终抛出 return true