You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. var typeOf = require('kind-of');
  3. /**
  4. * Basic sort algorithm that has similar behavior to `Array.prototype.sort`
  5. * for null and undefined, but also allows sorting by an object property.
  6. *
  7. * @param {Mixed} `a` First value to compare.
  8. * @param {Mixed} `b` Second value to compare.
  9. * @param {String} `prop` Optional property to use when comparing objects. If specified must be a string.
  10. * @return {Number} Returns 1 when `a` should come after `b`, -1 when `a` should come before `b`, and 0 when `a` and `b` are equal.
  11. * @api public
  12. */
  13. module.exports = function defaultCompare(a, b, prop) {
  14. if (prop != null && typeOf(prop) !== 'string') {
  15. throw new TypeError('expected "prop" to be undefined or a string');
  16. }
  17. var typeA = typeOf(a);
  18. var typeB = typeOf(b);
  19. if (prop) {
  20. if (typeA === 'object') {
  21. a = a[prop];
  22. typeA = typeOf(a);
  23. }
  24. if (typeB === 'object') {
  25. b = b[prop];
  26. typeB = typeOf(b);
  27. }
  28. }
  29. if (typeA === 'null') {
  30. return typeB === 'null' ? 0 : (typeB === 'undefined' ? -1 : 1);
  31. } else if (typeA === 'undefined') {
  32. return typeB === 'null' ? 1 : (typeB === 'undefined' ? 0 : 1);
  33. } else if (typeB === 'null' || typeB === 'undefined') {
  34. return -1;
  35. } else {
  36. return a < b ? -1 : (a > b ? 1 : 0);
  37. }
  38. };