Bài tập: Giỏ hàng readonly — tính tiền không sửa dữ liệu
Giỏ hàng được mô tả bằng các kiểu readonly (đã có trong code khởi đầu):
type CartItem = {
readonly sku: string;
readonly price: number;
readonly qty: number;
};
type Cart = {
readonly items: readonly CartItem[];
readonly couponPercent?: number;
};
type Summary = {
itemCount: number;
subtotal: number;
discount: number;
total: number;
mostExpensive: string | null;
};Viết summarizeCart(cart: Cart): Summary:
itemCount— tổngqtycủa mọi sản phẩm.subtotal— tổngprice * qty.discount—subtotal * couponPercent / 100, làm tròn bằngMath.round. Không có coupon →0; coupon lớn hơn50chỉ tính50.total—subtotal - discount.mostExpensive—skucủa dòng có thành tiền (price * qty) lớn nhất; nếu bằng nhau lấy dòng xuất hiện trước; giỏ rỗng →null.
Ví dụ
summarizeCart({
items: [
{ sku: "AO-01", price: 150000, qty: 2 },
{ sku: "MU-02", price: 50000, qty: 1 },
],
couponPercent: 10,
});
// { itemCount: 3, subtotal: 350000, discount: 35000, total: 315000, mostExpensive: "AO-01" }WARNING
Nhờ readonly, TypeScript báo lỗi nếu bạn gọi cart.items.sort(...) hay gán item.qty = .... Trình chấm còn đóng băng (Object.freeze) toàn bộ giỏ hàng, nên code sửa dữ liệu sẽ bị lỗi lúc chạy. Cần sắp xếp thì dùng toSorted — hoặc tốt hơn, một vòng lặp là đủ.
Examples
Example 1
Input
{"items":[{"sku":"AO-01","price":150000,"qty":2},{"sku":"MU-02","price":50000,"qty":1}],"couponPercent":10}Expected output
Số lượng: 3 Tạm tính: 350000 Giảm: 35000 Tổng: 315000 Đắt nhất: AO-01
Example 2
Input
{"items":[]}Expected output
Số lượng: 0 Tạm tính: 0 Giảm: 0 Tổng: 0 Đắt nhất: (không có)
6 hidden tests · Limit 2 s · 256 MB
type CartItem = {
readonly sku: string;
readonly price: number;
readonly qty: number;
};
type Cart = {
readonly items: readonly CartItem[];
readonly couponPercent?: number;
};
type Summary = {
itemCount: number;
subtotal: number;
discount: number;
total: number;
mostExpensive: string | null;
};
function summarizeCart(cart: Cart): Summary {
// ...
}
Comments