Search⌘ K
AI Features

Solution Review: Maps

Explore how to use the JavaScript Map object inside classes to manage key-value pairs efficiently. Understand creating, setting, and getting map elements, and build a function to count completed tasks by filtering map values.

We'll cover the following...

Solution

Let’s take a look at the solution.

Javascript (babel-node)
'use strict';
const createTodo = function() {
const todo = new Map();
todo.set('learn JavaScript', 'done');
todo.set('write elegant code', 'work-in-progress');
todo.set('automate tests', 'work-in-progress');
return todo;
};
const completedCount = function(map) {
return [...map.values()]
.filter(value => value === 'done')
.length;
};
const todo = createTodo(); //Returns a Map
console.log(todo.get('learn JavaScript')); //'done'
console.log(todo.get('write elegant code'));//'work-in-progress'
console.log(todo.get('automate tests'));//'work-in-progress'
console.log(completedCount(todo)); //1

Explanation

We needed to implement the Map data structure to get the exercise code running.

Map object

Let’s start by creating a map element. The Map object, todo, is created using the new keyword, as seen at line 4. Here, we are ...