sortBy.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import _curry2 from "./internal/_curry2.js";
  2. /**
  3. * Sorts the list according to the supplied function.
  4. *
  5. * @func
  6. * @memberOf R
  7. * @since v0.1.0
  8. * @category Relation
  9. * @sig Ord b => (a -> b) -> [a] -> [a]
  10. * @param {Function} fn
  11. * @param {Array} list The list to sort.
  12. * @return {Array} A new list sorted by the keys generated by `fn`.
  13. * @example
  14. *
  15. * const sortByFirstItem = R.sortBy(R.prop(0));
  16. * const pairs = [[-1, 1], [-2, 2], [-3, 3]];
  17. * sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]]
  18. *
  19. * const sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name')));
  20. * const alice = {
  21. * name: 'ALICE',
  22. * age: 101
  23. * };
  24. * const bob = {
  25. * name: 'Bob',
  26. * age: -10
  27. * };
  28. * const clara = {
  29. * name: 'clara',
  30. * age: 314.159
  31. * };
  32. * const people = [clara, bob, alice];
  33. * sortByNameCaseInsensitive(people); //=> [alice, bob, clara]
  34. */
  35. var sortBy =
  36. /*#__PURE__*/
  37. _curry2(function sortBy(fn, list) {
  38. return Array.prototype.slice.call(list, 0).sort(function (a, b) {
  39. var aa = fn(a);
  40. var bb = fn(b);
  41. return aa < bb ? -1 : aa > bb ? 1 : 0;
  42. });
  43. });
  44. export default sortBy;