uniqBy.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import _Set from "./internal/_Set.js";
  2. import _curry2 from "./internal/_curry2.js";
  3. import _dispatchable from "./internal/_dispatchable.js";
  4. import _xuniqBy from "./internal/_xuniqBy.js";
  5. /**
  6. * Returns a new list containing only one copy of each element in the original
  7. * list, based upon the value returned by applying the supplied function to
  8. * each list element. Prefers the first item if the supplied function produces
  9. * the same value on two items. [`R.equals`](#equals) is used for comparison.
  10. *
  11. * Acts as a transducer if a transformer is given in list position.
  12. *
  13. * @func
  14. * @memberOf R
  15. * @since v0.16.0
  16. * @category List
  17. * @sig (a -> b) -> [a] -> [a]
  18. * @param {Function} fn A function used to produce a value to use during comparisons.
  19. * @param {Array} list The array to consider.
  20. * @return {Array} The list of unique items.
  21. * @example
  22. *
  23. * R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10]
  24. */
  25. var uniqBy =
  26. /*#__PURE__*/
  27. _curry2(
  28. /*#__PURE__*/
  29. _dispatchable([], _xuniqBy, function (fn, list) {
  30. var set = new _Set();
  31. var result = [];
  32. var idx = 0;
  33. var appliedItem, item;
  34. while (idx < list.length) {
  35. item = list[idx];
  36. appliedItem = fn(item);
  37. if (set.add(appliedItem)) {
  38. result.push(item);
  39. }
  40. idx += 1;
  41. }
  42. return result;
  43. }));
  44. export default uniqBy;