6.1 KiB
Raw Blame History

id, title, challengeType, forumTopicId, localeTitle
id title challengeType forumTopicId localeTitle
8d5823c8c441eddfaeb5bdef Create a Map Data Structure 1 301629 Создание структуры данных карты

Description

Следующие несколько проблем будут охватывать карты и хеш-таблицы. Карты - это структуры данных, в которых хранятся пары ключ-значение. В JavaScript они доступны для нас как объекты. Карты обеспечивают быстрый поиск сохраненных элементов на основе значений ключей и являются очень распространенными и полезными структурами данных. Инструкции: Давайте попробуем создать собственную карту. Поскольку объекты JavaScript обеспечивают гораздо более эффективную структуру карты, чем все, что мы могли бы здесь написать, это в первую очередь предназначено для обучения. Однако объекты JavaScript предоставляют нам определенные операции. Что, если мы хотим определить пользовательские операции? Используйте объект Map указанный здесь как обертка вокруг object JavaScript. Создайте следующие методы и операции над объектом Map:
  • add принимает пару key, value для добавления на карту.
  • remove принимает ключ и удаляет связанную пару key, value
  • get принимает key и возвращает сохраненное value
  • has принимает key и возвращает истину , если ключ существует , или ложь , если она не делает.
  • values возвращают массив всех значений на карте
  • size возвращает количество элементов на карте
  • clear пустую карту

Instructions

Let's get some practice creating our own map. Because JavaScript objects provide a much more efficient map structure than anything we could write here, this is intended primarily as a learning exercise. However, JavaScript objects only provide us with certain operations. What if we wanted to define custom operations? Use the Map object provided here as a wrapper around a JavaScript object. Create the following methods and operations on the Map object:
  • add accepts a key, value pair to add to the map.
  • remove accepts a key and removes the associated key, value pair
  • get accepts a key and returns the stored value
  • has accepts a key and returns true if the key exists or false if it doesn't.
  • values returns an array of all the values in the map
  • size returns the number of items in the map
  • clear empties the map

Tests

tests:
  - text: The Map data structure exists.
    testString: assert((function() { var test = false; if (typeof Map !== 'undefined') { test = new Map() }; return (typeof test == 'object')})());
  - text: 'The Map object has the following methods: add, remove, get, has, values, clear, and size.'
    testString: 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')})());
  - text: The add method adds items to the map.
    testString: 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)})());
  - text: The has method returns true for added items and false for absent items.
    testString: assert((function() { var test = false; if (typeof Map !== 'undefined') { test = new Map() }; test.add('test','value'); return (test.has('test') && !test.has('false'))})());
  - text: The get method accepts keys as input and returns the associated values.
    testString: assert((function() { var test = false; if (typeof Map !== 'undefined') { test = new Map() }; test.add('abc','def'); return (test.get('abc') == 'def')})());
  - text: The values method returns all the values stored in the map as strings in an array.
    testString: 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)})());
  - text: The clear method empties the map and the size method returns the number of items present in the map.
    testString: 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)})());

Challenge Seed

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

Solution

// solution required