Check out this optimized solution that efficiently retrieves the nth key from a map:
function findNthKey<K, V>(map: Map<K, V>, index: number): K | undefined {
if (index < 0) {
return undefined;
}
const iterator = map.keys();
let count = index + 1;
for (;;) {
const result = iterator.next();
if (result.done) {
return undefined;
}
if (--count === 0) {
return result.value;
}
}
}
const myMap = new Map<string, string>([['item1', 'A'], ['item2', 'B'], ['item3', 'C']]);
console.log(findNthKey(myMap, -1));
console.log(findNthKey(myMap, 0));
console.log(findNthKey(myMap, 1));
console.log(findNthKey(myMap, 2));
console.log(findNthKey(myMap, 3));
Output:
undefined
item1
item2
item3
undefined