Resolvi trazer os metodos e propriedades existentes na class de Map para dentro do Dictionary com implementação própria para me desafiar. Adicionei inclusive o util.inspect.custom que é uma chave dentro do Node que me permite fazer um console.log do objeto diretamente, e assim eu decido a string a ser retornada, simulando o que acontece quando damos um log em um objeto do tipo Map.
const util = require('util');
class Dictionary {
#_keys;
#_values;
#_size;
constructor() {
this.#_keys = [];
this.#_values = [];
this.#_size = 0;
}
set(key, value) {
if (this.#_keys.indexOf(key) > -1) {
const keyIndex = this.#_keys.indexOf(key);
this.#_values[keyIndex] = value;
} else {
this.#_keys.push(key);
this.#_values.push(value);
this.#_size += 1;
}
}
get(chave) {
const keyIndex = this.#_keys.indexOf(chave);
if (keyIndex < 0) {
return null;
}
return this.#_values[keyIndex];
}
remove(key) {
const keyIndex = this.#_keys.indexOf(key);
if (keyIndex < 0) return null;
this.#_keys.splice(keyIndex, 1);
this.#_values.splice(keyIndex, 1);
this.#_size -= 1;
}
values() {
return [...this.#_values];
}
keys() {
return [...this.#_keys];
}
clear() {
this.#_keys = [];
this.#_values = [];
this.#_size = 0;
}
has(key) {
return (this.#_keys.indexOf(key) >= 0);
}
get size() {
return this.#_size;
}
[util.inspect.custom]() {
const entries = this.keys().map((k, i) => `${JSON.stringify(k)} => ${JSON.stringify(this.values()[i])}`);
return `Dictionary(${this.size}) {${entries.join(', ')}}`;
}
}