You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
689 B
JavaScript

"use strict";
module.exports = function generateLookupTable(items, getKey) {
let lookupTable = new Map();
function setItem(key, value) {
// TODO: Add a fast path for unique keys (no array wrapping), so that the index can contain both single items and arrays?
if (lookupTable.has(key)) {
lookupTable.get(key).push(value);
} else {
lookupTable.set(key, [ value ]);
}
}
items.forEach((item) => {
let key = getKey(item);
if (key != null) {
if (Array.isArray(key)) {
// This item should be available under multiple keys
for (let keyItem of key) {
setItem(keyItem, item);
}
} else {
setItem(key, item);
}
}
});
return lookupTable;
};