type Line = { id: string; qty: number };
type CartAction =
| { type: "added"; id: string }
| { type: "removed"; id: string }
| { type: "cleared" };
function cartReducer(lines: Line[], action: CartAction): Line[] {
switch (action.type) {
case "added":
return lines.some((l) => l.id === action.id)
? lines.map((l) => (l.id === action.id ? { ...l, qty: l.qty + 1 } : l))
: [...lines, { id: action.id, qty: 1 }];
case "removed":
return lines.filter((l) => l.id !== action.id);
case "cleared":
return [];
default: {
const unhandled: never = action;
throw new Error("Unknown action " + JSON.stringify(unhandled));
}
}
}
const show = (lines: Line[]) => lines.map((l) => l.id + "x" + l.qty).join(",") || "empty";
let cart: Line[] = [];
cart = cartReducer(cart, { type: "added", id: "tea" });
cart = cartReducer(cart, { type: "added", id: "cup" });
cart = cartReducer(cart, { type: "added", id: "tea" });
console.log(show(cart));
cart = cartReducer(cart, { type: "removed", id: "cup" });
console.log(show(cart));
const fromStorage = JSON.parse('{"type":"emptied"}') as CartAction;
try {
cart = cartReducer(cart, fromStorage);
} catch (error) {
console.log((error as Error).message);
}
console.log(show(cart));