« get me outta code hell

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
diff options
context:
space:
mode:
Diffstat (limited to 'util/count.js')
-rw-r--r--util/count.js17
1 files changed, 17 insertions, 0 deletions
diff --git a/util/count.js b/util/count.js
new file mode 100644
index 0000000..7df97a7
--- /dev/null
+++ b/util/count.js
@@ -0,0 +1,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
+}