4
1

compare.js 912 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. var strCompare = require('../string/#/case-insensitive-compare')
  3. , isObject = require('./is-object')
  4. , resolve, typeMap;
  5. typeMap = {
  6. undefined: 0,
  7. object: 1,
  8. boolean: 2,
  9. string: 3,
  10. number: 4
  11. };
  12. resolve = function (a) {
  13. if (isObject(a)) {
  14. if (typeof a.valueOf !== 'function') return NaN;
  15. a = a.valueOf();
  16. if (isObject(a)) {
  17. if (typeof a.toString !== 'function') return NaN;
  18. a = a.toString();
  19. if (typeof a !== 'string') return NaN;
  20. }
  21. }
  22. return a;
  23. };
  24. module.exports = function (a, b) {
  25. if (a === b) return 0; // Same
  26. a = resolve(a);
  27. b = resolve(b);
  28. if (a == b) return typeMap[typeof a] - typeMap[typeof b]; //jslint: ignore
  29. if (a == null) return -1;
  30. if (b == null) return 1;
  31. if ((typeof a === 'string') || (typeof b === 'string')) {
  32. return strCompare.call(a, b);
  33. }
  34. if ((a !== a) && (b !== b)) return 0; //jslint: ignore
  35. return Number(a) - Number(b);
  36. };