_compareMultiple.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var compareAscending = require('./_compareAscending');
  2. /**
  3. * Used by `_.orderBy` to compare multiple properties of a value to another
  4. * and stable sort them.
  5. *
  6. * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
  7. * specify an order of "desc" for descending or "asc" for ascending sort order
  8. * of corresponding values.
  9. *
  10. * @private
  11. * @param {Object} object The object to compare.
  12. * @param {Object} other The other object to compare.
  13. * @param {boolean[]|string[]} orders The order to sort by for each property.
  14. * @returns {number} Returns the sort order indicator for `object`.
  15. */
  16. function compareMultiple(object, other, orders) {
  17. var index = -1,
  18. objCriteria = object.criteria,
  19. othCriteria = other.criteria,
  20. length = objCriteria.length,
  21. ordersLength = orders.length;
  22. while (++index < length) {
  23. var result = compareAscending(objCriteria[index], othCriteria[index]);
  24. if (result) {
  25. if (index >= ordersLength) {
  26. return result;
  27. }
  28. var order = orders[index];
  29. return result * (order == 'desc' ? -1 : 1);
  30. }
  31. }
  32. // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
  33. // that causes it, under certain circumstances, to provide the same value for
  34. // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
  35. // for more details.
  36. //
  37. // This also ensures a stable sort in V8 and other engines.
  38. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
  39. return object.index - other.index;
  40. }
  41. module.exports = compareMultiple;