# 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.

- Category: performance
- Level: warning
- Fix: suggestion
- Scope: module

## Reported

```ds title="main.ds"
import { Map } from "destack:collections";

function ensureValue(values: Map<string, int32>, key: string): void {
    if (!values.has(key)) {
        values.set(key, 1);
    }
}
```

## Accepted

```ds title="main.ds"
import { Map } from "destack:collections";

function ensureValue(values: Map<string, int32>, key: string): void {
    values.getOrInsertWith(key, () => 1);
}
```

## Prior art

- [Clippy · map_entry](https://rust-lang.github.io/rust-clippy/master/index.html#map_entry)

[language/linter/src/rules/performance/prefer_map_entry.rs:8](https://github.com/destack-sh/destack/blob/main/language/linter/src/rules/performance/prefer_map_entry.rs#L8)
