Sitemap
Alex Ercolin

Alex Ercolin

.........

How the set Method from Map is Implemented in C++ by V8 JavaScript

4 min readFeb 8, 2025

This is the first part of a series of articles where I will detail the JavaScript HashMap implementation using new Map() and how it works under the hood with the V8 C++ implementation. Today, we will deep dive into the set() method.

Basically, the set() method is used to add key-value pairs to a Map object, but it can also be used to update the value of an existing key. It's important to remember that, as we are talking about a HashMap, there always exist unique keys.

So, let’s code. First, let’s see how it works in JavaScript.

const brazilianChampions = new Map();

brazilianChampions.set("Palmeiras", 12);
brazilianChampions.set("Santos", 8);
brazilianChampions.set("Corinthians", 7);
brazilianChampions.set("Flamengo", 7);

console.log("brazilianChampions", brazilianChampions);
// Output
// brazilianChampions Map(4) {
// 'Palmeiras' => 12,
// 'Santos' => 8,
// 'Corinthians' => 7,
// 'Flamengo' => 7
// }

It’s pretty simple. We just create a const variable and assign it a new Map(). Afterward, we use the set method to add key-value pairs. Finally, we log our hashMap to see how it's built.

At a glance, we see that it is very easy to use, but how did the V8 developers implement it? Let’s dive in.

This is theOrderedHashSet::Add function declared here.

MaybeHandle<OrderedHashSet> OrderedHashSet::Add(Isolate* isolate,
Handle<OrderedHashSet> table,
Handle<Object> key) {
int hash = key->GetOrCreateHash(isolate).value();
int entry = table->HashToEntry(hash);
// Walk the chain of the bucket and try finding the key.
while (entry != kNotFound) {
Object candidate_key = table->KeyAt(entry);
// Do not add if we have the key already
if (candidate_key.SameValueZero(*key)) return table;
entry = table->NextChainEntry(entry);
}

MaybeHandle<OrderedHashSet> table_candidate =
OrderedHashSet::EnsureGrowable(isolate, table);
if (!table_candidate.ToHandle(&table)) {
return table_candidate;
}
// Read the existing bucket values.
int bucket = table->HashToBucket(hash);
int previous_entry = table->HashToEntry(hash);
int nof = table->NumberOfElements();
// Insert a new entry at the end,
int new_entry = nof + table->NumberOfDeletedElements();
int new_index = table->EntryToIndex(new_entry);
table->set(new_index, *key);
table->set(new_index + kChainOffset, Smi::FromInt(previous_entry));
// and point the bucket to the new entry.
table->set(HashTableStartIndex() + bucket, Smi::FromInt(new_entry));
table->SetNumberOfElements(nof + 1);
return table;
}

So, let’s analyze step by step together.

Get Alex Ercolin’s stories in your inbox

Join Medium for free to get updates from this writer.

First of all, try to get or create a hash for the key and assign it to int hash

  int hash = key->GetOrCreateHash(isolate).value();
int entry = table->HashToEntry(hash);
// Walk the chain of the bucket and try finding the key.
while (entry != kNotFound) {
Object candidate_key = table->KeyAt(entry);
// Do not add if we have the key already
if (candidate_key.SameValueZero(*key)) return table;
entry = table->NextChainEntry(entry);
}

MaybeHandle<OrderedHashSet> table_candidate =
OrderedHashSet::EnsureGrowable(isolate, table);
if (!table_candidate.ToHandle(&table)) {
return table_candidate;
}

And loop through the table to find the key to handle collisions and chaining. Remember that we said that a HashMap only has unique keys? So, this is the part of the code that handles this. If the key already exists, just return the current table. But now, if the key does not exist…

// Read the existing bucket values.
int bucket = table->HashToBucket(hash);
int previous_entry = table->HashToEntry(hash);
int nof = table->NumberOfElements();
// Insert a new entry at the end,
int new_entry = nof + table->NumberOfDeletedElements();
int new_index = table->EntryToIndex(new_entry);
table->set(new_index, *key);
table->set(new_index + kChainOffset, Smi::FromInt(previous_entry));
// and point the bucket to the new entry.
table->set(HashTableStartIndex() + bucket, Smi::FromInt(new_entry));
table->SetNumberOfElements(nof + 1);
return table;
}

First, we need to ensure growth: If the key is not present, it calls OrderedHashSet::EnsureGrowable to make sure the table has enough capacity to add a new entry. If necessary, the table can be resized.

  int bucket = table->HashToBucket(hash);
int previous_entry = table->HashToEntry(hash);
int nof = table->NumberOfElements();
// Insert a new entry at the end,
int new_entry = nof + table->NumberOfDeletedElements();
int new_index = table->EntryToIndex(new_entry);
table->set(new_index, *key);
table->set(new_index + kChainOffset, Smi::FromInt(previous_entry));
// and point the bucket to the new entry.
table->set(HashTableStartIndex() + bucket, Smi::FromInt(new_entry));
table->SetNumberOfElements(nof + 1);
return table;

Now, we need to read the values from the bucket to prepare for the element insertion. So, we created three variables: bucket to convert the hash into a bucket index, previous_entry to get the previous entry from the bucket, and nof to get the number of elements in the table.

Now, the new_entry will be the sum of the number of elements and the number of deleted elements, and new_index will be the entry index converted into the table index. Finally, insert the key into the table with the appropriate chaining.

To finalize, increment the bucket index to point to the new entry and increment the number of elements in the table, returning everything.

Basically, that is it. In the next article, we will see how the get method works.

--

--