3.0 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 691b559495c5cb5a37b9b484 | Challenge 124: Inventory Update | 28 | challenge-124 |
--description--
Given a 2D array representing the inventory of your store, and another 2D array representing a shipment you have received, return your updated inventory.
- Each element in the arrays will have the format:
[quantity, "item"], wherequantityis an integer and"item"is a string. - Update items in the inventory by adding the quantity of any matching items from the shipment.
- If a received item does not exist in the current inventory, add it as a new entry to the end of the inventory.
- Return inventory in the order it was given with new items at the end in the order they appear in the shipment.
For example, given an inventory of [[2, "apples"], [5, "bananas"]] and a shipment of [[1, "apples"], [3, "bananas"]], return [[3, "apples"], [8, "bananas"]].
--hints--
updateInventory([[2, "apples"], [5, "bananas"]], [[1, "apples"], [3, "bananas"]]) should return [[3, "apples"], [8, "bananas"]].
assert.deepEqual(updateInventory([[2, "apples"], [5, "bananas"]], [[1, "apples"], [3, "bananas"]]), [[3, "apples"], [8, "bananas"]]);
updateInventory([[2, "apples"], [5, "bananas"]], [[1, "apples"], [3, "bananas"], [4, "oranges"]]) should return [[3, "apples"], [8, "bananas"], [4, "oranges"]].
assert.deepEqual(updateInventory([[2, "apples"], [5, "bananas"]], [[1, "apples"], [3, "bananas"], [4, "oranges"]]), [[3, "apples"], [8, "bananas"], [4, "oranges"]]);
updateInventory([], [[10, "apples"], [30, "bananas"], [20, "oranges"]]) should return [[10, "apples"], [30, "bananas"], [20, "oranges"]].
assert.deepEqual(updateInventory([], [[10, "apples"], [30, "bananas"], [20, "oranges"]]), [[10, "apples"], [30, "bananas"], [20, "oranges"]]);
updateInventory([[0, "Bowling Ball"], [0, "Dirty Socks"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]]) should return [[1, "Bowling Ball"], [0, "Dirty Socks"], [1, "Hair Pin"], [0, "Microphone"], [1, "Half-Eaten Apple"], [1, "Toothpaste"]].
assert.deepEqual(updateInventory([[0, "Bowling Ball"], [0, "Dirty Socks"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]]), [[1, "Bowling Ball"], [0, "Dirty Socks"], [1, "Hair Pin"], [0, "Microphone"], [1, "Half-Eaten Apple"], [1, "Toothpaste"]]);
--seed--
--seed-contents--
function updateInventory(inventory, shipment) {
return inventory;
}
--solutions--
function updateInventory(inventory, shipment) {
const inventoryMap = new Map();
inventory.forEach(([qty, item], index) => {
inventoryMap.set(item, index);
});
shipment.forEach(([qty, item]) => {
if (inventoryMap.has(item)) {
const index = inventoryMap.get(item);
inventory[index][0] += qty;
} else {
inventory.push([qty, item]);
inventoryMap.set(item, inventory.length - 1);
}
});
return inventory;
}