compare.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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 = { undefined: 0, object: 1, boolean: 2, string: 3, number: 4 };
  9. resolve = function (a) {
  10. if (isObject(a)) {
  11. if (typeof a.valueOf !== "function") return NaN;
  12. a = a.valueOf();
  13. if (isObject(a)) {
  14. if (typeof a.toString !== "function") return NaN;
  15. a = a.toString();
  16. if (typeof a !== "string") return NaN;
  17. }
  18. }
  19. return a;
  20. };
  21. module.exports = function (val1, val2) {
  22. if (val1 === val2) return 0; // Same
  23. val1 = resolve(val1);
  24. val2 = resolve(val2);
  25. // eslint-disable-next-line eqeqeq
  26. if (val1 == val2) return typeMap[typeof val1] - typeMap[typeof val2];
  27. if (!isValue(val1)) return -1;
  28. if (!isValue(val2)) return 1;
  29. if (typeof val1 === "string" || typeof val2 === "string") {
  30. return strCompare.call(val1, val2);
  31. }
  32. if (numIsNaN(val1) && numIsNaN(val2)) return 0; // Jslint: ignore
  33. return Number(val1) - Number(val2);
  34. };