« get me outta code hell

count.js « util - tui-lib - Pure Node.js library for making visual command-line programs (ala vim, ncdu)
about summary refs log tree commit diff
path: root/util/count.js
blob: 7df97a7affadb2048b72773c2901f1672e8eac44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module.exports = function count(arr) {
  // Counts the number of times the items of an array appear (only on the top
  // level; it doesn't search through nested arrays!). Returns a map of
  // item -> count.

  const map = new Map()

  for (let item of arr) {
    if (map.has(item)) {
      map.set(item, map.get(item) + 1)
    } else {
      map.set(item, 1)
    }
  }

  return map
}