compareMultiple.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var baseCompareAscending = require('./baseCompareAscending');
  2. /**
  3. * Used by `_.sortByOrder` to compare multiple properties of a value to another
  4. * and stable sort them.
  5. *
  6. * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
  7. * a value is sorted in ascending order if its corresponding order is "asc", and
  8. * descending if "desc".
  9. *
  10. * @private
  11. * @param {Object} object The object to compare.
  12. * @param {Object} other The other object to compare.
  13. * @param {boolean[]} 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 = baseCompareAscending(objCriteria[index], othCriteria[index]);
  24. if (result) {
  25. if (index >= ordersLength) {
  26. return result;
  27. }
  28. var order = orders[index];
  29. return result * ((order === 'asc' || order === true) ? 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://code.google.com/p/v8/issues/detail?id=90 for more details.
  39. return object.index - other.index;
  40. }
  41. module.exports = compareMultiple;