countBy.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. import reduceBy from "./reduceBy.js";
  2. /**
  3. * Counts the elements of a list according to how many match each value of a
  4. * key generated by the supplied function. Returns an object mapping the keys
  5. * produced by `fn` to the number of occurrences in the list. Note that all
  6. * keys are coerced to strings because of how JavaScript objects work.
  7. *
  8. * Acts as a transducer if a transformer is given in list position.
  9. *
  10. * @func
  11. * @memberOf R
  12. * @since v0.1.0
  13. * @category Relation
  14. * @sig (a -> String) -> [a] -> {*}
  15. * @param {Function} fn The function used to map values to keys.
  16. * @param {Array} list The list to count elements from.
  17. * @return {Object} An object mapping keys to number of occurrences in the list.
  18. * @example
  19. *
  20. * const numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];
  21. * R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}
  22. *
  23. * const letters = ['a', 'b', 'A', 'a', 'B', 'c'];
  24. * R.countBy(R.toLower)(letters); //=> {'a': 3, 'b': 2, 'c': 1}
  25. */
  26. var countBy =
  27. /*#__PURE__*/
  28. reduceBy(function (acc, elem) {
  29. return acc + 1;
  30. }, 0);
  31. export default countBy;