menu

prefer-map-entry

Prefer one map entry operation over a guarded insertion

Checking a map before inserting a missing value performs the same key lookup twice. Instead, you SHOULD use getOrInsertWith to combine the lookup and conditional insertion.

Reported

1import { Map } from "destack:collections";2 3function ensureValue(values: Map<string, int32>, key: string): void {4    if (!values.has(key)) {5        values.set(key, 1);6    }7}

Accepted

1import { Map } from "destack:collections";2 3function ensureValue(values: Map<string, int32>, key: string): void {4    values.getOrInsertWith(key, () => 1);5}