Skip to content

Commit

Permalink
Fix: Rekey in Rekeyable map shouldn't keep target item if rekeying to…
Browse files Browse the repository at this point in the history
… existing key (#2607)

fix [#2489](#2489)
  • Loading branch information
timotheeguerin authored Nov 1, 2023
1 parent 7d2ec8b commit dc95c54
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@typespec/compiler",
"comment": "[Internal] Fix: `RekeyableMap` kept track of old value if rekeying to an existing item",
"type": "none"
}
],
"packageName": "@typespec/compiler"
}
4 changes: 4 additions & 0 deletions packages/compiler/src/core/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,10 @@ class RekeyableMapImpl<K, V> implements RekeyableMap<K, V> {
return false;
}
this.#keys.delete(existingKey);
const newKeyItem = this.#keys.get(newKey);
if (newKeyItem) {
this.#values.delete(newKeyItem);
}
keyItem.key = newKey;
this.#keys.set(newKey, keyItem);
return true;
Expand Down
20 changes: 20 additions & 0 deletions packages/compiler/test/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,25 @@ describe("compiler: util", () => {
]
);
});

it("rekeying to existing key override the target", () => {
const map = createRekeyableMap([
["a", "pos 1"],
["b", "pos 2"],
["c", "pos 3"],
["d", "pos 4"],
]);

map.rekey("c", "b");

deepStrictEqual(
[...map.entries()],
[
["a", "pos 1"],
["b", "pos 3"],
["d", "pos 4"],
]
);
});
});
});

0 comments on commit dc95c54

Please sign in to comment.