freeCodeCamp/curriculum/challenges/portuguese/10-coding-interview-prep/data-structures/create-a-map-data-structure.md

5.0 KiB

id title challengeType forumTopicId dashedName
8d5823c8c441eddfaeb5bdef Criar uma estrutura de dados de mapa 1 301629 create-a-map-data-structure

--description--

Os próximos desafios tratarão de mapas e tabelas hash. Mapas são estruturas de dados que armazenam pares chave-valor. Em JavaScript, essas estruturas estão disponíveis para nós como objetos. Mapas fornecem uma busca rápida de itens armazenados com base em valores chave e são estruturas de dados muito comuns e úteis.

--instructions--

Vamos praticar um pouco criando nosso próprio mapa. Como objetos JavaScript fornecem uma estrutura de mapa muito mais eficiente do que qualquer outra que pudéssemos escrever aqui, o objetivo aqui é, principalmente, um exercício de aprendizagem. No entanto, objetos JavaScript nos fornecem apenas algumas operações. E se quiséssemos definir operações personalizadas? Use o objeto Map fornecido aqui para envolver o object de JavaScript. Criar os seguintes métodos e operações no objeto Map:

  • add aceita um par key, value para adicioná-lo ao mapa.
  • remove aceita uma chave e remove o par key, value associado
  • get aceita uma key e retorna o value armazenado
  • has aceita uma key e retorna true, se a chave existir no mapa, ou false, se ela não existir.
  • values retorna um array de todos os valores no mapa
  • size retorna o número de itens no mapa
  • clear esvazia o mapa

--hints--

A estrutura de dados Map deve existir.

assert(
  (function () {
    var test = false;
    if (typeof Map !== 'undefined') {
      test = new Map();
    }
    return typeof test == 'object';
  })()
);

O objeto Map deve ter os seguintes métodos: add, remove, get, has, values, clear e size.

assert(
  (function () {
    var test = false;
    if (typeof Map !== 'undefined') {
      test = new Map();
    }
    return (
      typeof test.add == 'function' &&
      typeof test.remove == 'function' &&
      typeof test.get == 'function' &&
      typeof test.has == 'function' &&
      typeof test.values == 'function' &&
      typeof test.clear == 'function' &&
      typeof test.size == 'function'
    );
  })()
);

O método add deve adicionar itens ao mapa.

assert(
  (function () {
    var test = false;
    if (typeof Map !== 'undefined') {
      test = new Map();
    }
    test.add(5, 6);
    test.add(2, 3);
    test.add(2, 5);
    return test.size() == 2;
  })()
);

O método has deve retornar true para itens adicionados e false para itens ausentes.

assert(
  (function () {
    var test = false;
    if (typeof Map !== 'undefined') {
      test = new Map();
    }
    test.add('test', 'value');
    return test.has('test') && !test.has('false');
  })()
);

O método get deve aceitar chaves como entrada e deve retornar os valores associados.

assert(
  (function () {
    var test = false;
    if (typeof Map !== 'undefined') {
      test = new Map();
    }
    test.add('abc', 'def');
    return test.get('abc') == 'def';
  })()
);

O método values deve retornar todos os valores armazenados no mapa como strings em um array.

assert(
  (function () {
    var test = false;
    if (typeof Map !== 'undefined') {
      test = new Map();
    }
    test.add('a', 'b');
    test.add('c', 'd');
    test.add('e', 'f');
    var vals = test.values();
    return (
      vals.indexOf('b') != -1 &&
      vals.indexOf('d') != -1 &&
      vals.indexOf('f') != -1
    );
  })()
);

O método clear deve esvaziar o mapa e o método size deve retornar o número de itens presentes no mapa.

assert(
  (function () {
    var test = false;
    if (typeof Map !== 'undefined') {
      test = new Map();
    }
    test.add('b', 'b');
    test.add('c', 'd');
    test.remove('asdfas');
    var init = test.size();
    test.clear();
    return init == 2 && test.size() == 0;
  })()
);

--seed--

--seed-contents--

var Map = function() {
  this.collection = {};
  // Only change code below this line

  // Only change code above this line
};

--solutions--

var Map = function() {
    this.collection = {};
    // Only change code below this line

    this.add = function(key,value) {
      this.collection[key] = value;
    }

    this.remove = function(key) {
      delete this.collection[key];
    }

    this.get = function(key) {
      return this.collection[key];
    }

    this.has = function(key) {
      return this.collection.hasOwnProperty(key)
    }

    this.values = function() {
      return Object.values(this.collection);
    }

    this.size = function() {
      return Object.keys(this.collection).length;
    }

    this.clear = function() {
      for(let item of Object.keys(this.collection)) {
        delete this.collection[item];
      }
    }
    // Only change code above this line
};