这是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;
};
网友评论