compare.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. var strCompare = require("../string/#/case-insensitive-compare")
  3. , isObject = require("./is-object")
  4. , isValue = require("./is-value")
  5. , numIsNaN = require("../number/is-nan")
  6. , resolve
  7. , typeMap;
  8. typeMap = {
  9. undefined: 0,
  10. object: 1,
  11. boolean: 2,
  12. string: 3,
  13. number: 4
  14. };
  15. resolve = function (a) {
  16. if (isObject(a)) {
  17. if (typeof a.valueOf !== "function") return NaN;
  18. a = a.valueOf();
  19. if (isObject(a)) {
  20. if (typeof a.toString !== "function") return NaN;
  21. a = a.toString();
  22. if (typeof a !== "string") return NaN;
  23. }
  24. }
  25. return a;
  26. };
  27. module.exports = function (val1, val2) {
  28. if (val1 === val2) return 0; // Same
  29. val1 = resolve(val1);
  30. val2 = resolve(val2);
  31. // eslint-disable-next-line eqeqeq
  32. if (val1 == val2) return typeMap[typeof val1] - typeMap[typeof val2];
  33. if (!isValue(val1)) return -1;
  34. if (!isValue(val2)) return 1;
  35. if (typeof val1 === "string" || typeof val2 === "string") {
  36. return strCompare.call(val1, val2);
  37. }
  38. if (numIsNaN(val1) && numIsNaN(val2)) return 0; // Jslint: ignore
  39. return Number(val1) - Number(val2);
  40. };