Hash join
Implement hashJoin(left, right, leftKey, rightKey), an inner join of two arrays of rows, as a database runs it. For each left row, in order, output one merged row { ...leftRow, ...rightRow } for every right row, in order, where leftRow[leftKey] equals rightRow[rightKey]. Keys match by value and type, so 1 does not match '1'. A null or missing key never matches anything, as in SQL. Build an index of one side first so the join takes time proportional to the rows, not their product. Do not change the input rows.
Start from
function hashJoin(left, right, leftKey, rightKey) {
// Index one side, then walk the other.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Index the right rows in a Map from key to an array of rows, skipping rows whose key is null or undefined.
Hint 2
A Map compares keys by value and type; a plain object would turn 1 and '1' into the same key.
Hint 3
Then walk the left rows in order and spread each match into a new object.
Solution
The app has this lab in JavaScript, TypeScript and Python. This page shows the JavaScript code.
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function hashJoin(left, right, leftKey, rightKey) {
const index = new Map();
for (const row of right) {
const key = row[rightKey];
if (key === null || key === undefined) continue;
if (!index.has(key)) index.set(key, []);
index.get(key).push(row);
}
const out = [];
for (const row of left) {
const key = row[leftKey];
if (key === null || key === undefined) continue;
for (const match of index.get(key) || []) out.push({ ...row, ...match });
}
return out;
}What an interviewer looks for
Joins are what databases spend their time on, and backend interviews ask how a join is executed. Writing a hash join shows why an index turns a nested loop into one pass, and why NULL never equals NULL.