← All lints

counter_by_map

L0579Idiomswarn

Map used as a counter

cnt[x] = (cnt.get(x) ?? 0) + 1 on a Map<K, Int>: Counter<K> (std.hashmap)

Flagged
let a = [3, 1, 3, 2, 3]
var cnt: Map<Int, Int> = Map()
for x in a:
    cnt[x] = (cnt.get(x) ?? 0) + 1
print(cnt[3])
Write instead
let a = [3, 1, 3, 2, 3]
var cnt = Counter<Int>(0)
for x in a:
    cnt.push(x)
print(cnt[3])

Why

A Map<K, Int> that is only ever bumped with cnt[x] = (cnt.get(x) ?? 0) + 1 is a counter written by hand: every update repeats the key and the ?? 0. Counter<K> (std.hashmap) is the counter itself: var cnt = Counter<K>(0) starts it, cnt.push(x) adds 1, cnt.add(x, d) adds d, and cnt[x] reads 0 for a key it never saw, all O(1)O(1) expected. It is hashed, so keep the Map when you walk the counts in key order.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.sorted: sets, bags, maps, intervals.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let a = [3, 1, 3, 2, 3]
var cnt: Map<Int, Int> = Map()
for x in a:
    cnt[x] = (cnt.get(x - 1) ?? 0) + 1
var best: Map<Int, Int> = Map()
for x in a:
    best[x] = (best.get(x) ?? 5) + 1
print(cnt[3], best[3])

Turn it off

For one block, wrap it in with lint(counter_by_map: allow):. For a project, add counter_by_map = "allow" under [lints] in cp.toml.

Generated from spec/lints/counter_by_map, the same record the linter is built from.