美文网首页666笔记侠
57/666 HJDS npm read | is-sorted

57/666 HJDS npm read | is-sorted

作者: 红叔笔记 | 来源:发表于2018-10-14 06:05 被阅读0次

    这是666计划的57篇笔记

    nodejs sort

    demo.js:

    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
    

    index.js:

    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
    }
    

    nodejs array first

    demo.js:

    var first = require('array-first');
    
    first(['a', 'b', 'c', 'd', 'e', 'f']);
    //=> 'a'
    
    first(['a', 'b', 'c', 'd', 'e', 'f'], 1);
    //=> 'a'
    
    first(['a', 'b', 'c', 'd', 'e', 'f'], 3);
    //=> ['a', 'b', 'c']
    

    index.js:

    var isNumber = require('is-number');
    var slice = require('array-slice');
    
    module.exports = function arrayFirst(arr, num) {
      if (!Array.isArray(arr)) {
        throw new Error('array-first expects an array as the first argument.');
      }
    
      if (arr.length === 0) {
        return null;
      }
    
      var first = slice(arr, 0, isNumber(num) ? +num : 1);
      if (+num === 1 || num == null) {
        return first[0];
      }
      return first;
    };
    

    相关文章

      网友评论

        本文标题:57/666 HJDS npm read | is-sorted

        本文链接:https://www.haomeiwen.com/subject/edtzaftx.html