>>109612371
Corrected version:
const actions = [
{ type: "add", item: "potion", amount: 3 },
{ type: "add", item: "sword", amount: 1 },
{ type: "use", item: "potion", amount: 1 },
{ type: "add", item: "potion", amount: 2 },
{ type: "drop", item: "sword", amount: 1 },
{ type: "use", item: "potion", amount: 3 },
{ type: "use", item: "potion", amount: 3 },
{ type: "add", item: "sword", amount: 3 },
{ type: "drop", item: "sword", amount: 2 },
{ type: "drop", item: "potion", amount: 1 },
];
const filterRecord = (record, predicate) => Object.fromEntries(Object.entries(record).filter(predicate));
const verbToPastMap = {
"drop": "dropped",
"use": "used",
"add": "added"
};
const toVerbPast = (actionType) => {
if (Object.hasOwn(verbToPastMap, actionType)) return verbToPastMap[actionType];
throw Error(`Encountered unimplemented action type: '${actionType}'`);
}
const capitalizeFirstLetter = (str) => (str.at(0) ?? "").toUpperCase().concat(str.slice(1));
const toLog = (actionType, isActionSuccessful, amount, item) => {
const computedAction = isActionSuccessful ? toVerbPast(actionType) : `couldn't ${actionType}`;
return capitalizeFirstLetter(`${computedAction} ${amount} ${item}`);
}
const actionsReducer = ({inventory, log}, {type, item, amount}) => {
const currentItemAmount = inventory[item] ?? 0;
const computedItemAmount = type === "add" ? currentItemAmount + amount : currentItemAmount - amount;
const isActionSuccessful = computedItemAmount >= 0;
const correctedItemAmount = isActionSuccessful ? computedItemAmount : currentItemAmount;
const newInventory = filterRecord({...inventory, [item]: correctedItemAmount}, ([_item, amount]) => amount > 0);
const newLog = log.concat(toLog(type, isActionSuccessful, amount, item));
return { inventory: newInventory, log: newLog };
}
const reduceActions = (actions) => actions.reduce(actionsReducer, {inventory: {}, log: []});
console.log(reduceActions(actions));