« 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: 24c11b03e4f1f93eb645bda5778a019cdc517ecd (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 (const item of arr) {
    if (map.has(item)) {
      map.set(item, map.get(item) + 1)
    } else {
      map.set(item, 1)
    }
  }

  return map
}