« 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: d4c0919d3651baaf75c7d809f4d7bd3c5408c8d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export default 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 (const item of arr) {
    if (map.has(item)) {
      map.set(item, map.get(item) + 1)
    } else {
      map.set(item, 1)
    }
  }

  return map
}