My apologies if this is a duplicate. I didn't find an answer elsewhere.
Ramda.js provides the countBy() function. From the documentation we can see:
const R = require("ramda")
const letters = ['a', 'b', 'A', 'a', 'B', 'c'];
R.countBy(R.toLower)(letters); //=> {'a': 3, 'b': 2, 'c': 1}
But what if we already have our letters in lowercase? That is, we don't need any extra step, but just to count. For example, let's say I want to simply count letters2 array:
const letters2 = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]
R.countBy(letters2) // doesn't work
Instead, we must add some identity expression such as:
R.countBy(x => x)(letters2)
// gives {"a": 4, "b": 2, "c": 4}
or
R.countBy(R.identity)(letters2)
This isn't always the case with other Ramda functions (e.g., R.isNil()). I'm trying to understand where this extra step of identity comes from. To me it seems unnecessary, but I'm probably missing something.
Thanks!
The reason is that ramda simply does not make any assumption on how you want to count your list...
const list = ['A', 'b', 'c', 'D', 'e', 'f', 'g', 'G', 'F'];
// simply count
console.log(
R.countBy(R.identity, list),
)
// or count case insensitively
console.log(
R.countBy(R.toLower, list),
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.js" integrity="sha512-ZZcBsXW4OcbCTfDlXbzGCamH1cANkg6EfZAN2ukOl7s5q8skbB+WndmAqFT8fuMzeuHkceqd5UbIDn7fcqJFgg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Also, do not forget that you can build up your functions by leveraging partial application.
Note the wording, countBy as if Ramda wants to be told how to count. but nothing prevents you from building your own count.
const count = R.countBy(R.identity);
console.log(count(list))