-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCartStore.ts
216 lines (181 loc) · 5.28 KB
/
CartStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { createEffect, createMemo, createSignal, on } from 'solid-js';
import { createStore, unwrap } from 'solid-js/store';
import { formatCurrency } from '../lib/helpers';
import type { Accessor } from 'solid-js';
import type { Store } from 'solid-js/store';
import type { Book, BookId, BookState } from './BookStore';
// At this point stores only support
// nested reactivity an arrays
// and plain objects
type Item = {
book: Book;
quantity: number;
};
function makeItem(book: Book, quantity: number) {
return {
book,
quantity,
};
}
function itemPrice(item: Item) {
return item.quantity * item.book.price;
}
function itemIsValid(item: Item) {
return item.book.isAvailable;
}
function itemToJson(item: Item) {
return {
id: item.book.id,
quantity: item.quantity,
};
}
type ItemJson = ReturnType<typeof itemToJson>;
type CartState = Item[];
type SendNotice = (text: string) => void;
type AddItem = (id: BookId, quantity?: number, notify?: boolean) => void;
type UpdateItem = (id: BookId, quantity: string) => void;
type CartStore = [
Store<Item[]>,
{
loading: Accessor<boolean>;
subTotal: Accessor<number>;
discount: Accessor<number>;
total: Accessor<number>;
canCheckout: Accessor<boolean>;
addItem: AddItem;
updateItem: UpdateItem;
checkout(notify?: boolean): void;
}
];
type CartStorage = {
load: () => Promise<string | undefined | null>;
save: (json: string) => Promise<void>;
};
function createCartStore(
booksLoading: Accessor<boolean>,
books: Store<BookState>,
storage?: CartStorage,
send?: SendNotice
): CartStore {
const [items, setItems] = createStore<CartState>([]);
const subTotal = createMemo(() => items.reduce(addItemPrice, 0));
const discount = createMemo(() => (subTotal() >= 100 ? subTotal() * 0.1 : 0));
const total = createMemo(() => subTotal() - discount());
const canCheckout = createMemo(
() => items.length > 0 && items.every(isValidForCheckout)
);
// Cart Storage Management
let initialized = false;
let lastBooksLoading = true;
const [loading, setLoading] = createSignal(true);
createEffect(
on(booksLoading, () => {
if (booksLoading()) {
// transition to loadING
if (!lastBooksLoading) setLoading(true);
lastBooksLoading = true;
return;
}
// No transition - nothing to do
if (!lastBooksLoading) return;
// Transition to loadED
lastBooksLoading = false;
if (initialized || !storage) {
// Nothing to load
setLoading(false);
initialized = true;
return;
}
// Load from storage after first books load
storage.load().then(loadCart);
})
);
// Keep saving cart if storage present
if (storage) {
const json = createMemo(() => items.reduce(pushValidItemJson, []));
createEffect(
on(json, () => {
if (loading()) return;
storage.save(JSON.stringify(json()));
})
);
}
return [
items,
{
loading,
subTotal,
total,
discount,
canCheckout,
addItem,
updateItem,
checkout: (notify = true) => {
const totalAmount = total();
setItems([]);
if (notify && send)
send(`Bought books for ${formatCurrency(totalAmount)}!`);
},
},
];
// ---
function addItem(id: BookId, quantity = 1, notify = true): void {
const data = unwrap(items);
const index = data.findIndex((item) => item.book.id === id);
if (index > -1) {
// Add specified quantity to existing item
const item = data[index];
const newQuantity = item.quantity + quantity;
setItems(index, 'quantity', newQuantity);
if (notify && send)
send(`Updated "${item.book.name}" quantity to ${newQuantity}`);
return;
}
const book = books[id];
if (!book) return;
// Create a new item
const newItem = makeItem(book, quantity);
setItems(items.concat(newItem));
if (notify && send) send(`Added (${quantity}) of "${book.name}"`);
}
function updateItem(id: BookId, value: string) {
const quantity = Number.parseInt(value, 10);
if (Number.isNaN(quantity)) return;
const data = unwrap(items);
const index = data.findIndex((item) => item.book.id === id);
if (index < 0) return;
if (quantity > 0) {
// Replace quantity
setItems(index, 'quantity', quantity);
return;
}
// Remove item
setItems(data.filter((item) => item.book.id !== id));
}
function loadCart(json: string | undefined | null): void {
const rawItems: ItemJson[] = JSON.parse(json ?? '[]');
const items = rawItems.reduce(
(array: CartState, { id, quantity }: ItemJson) => {
const book = books[id];
if (book) array.push(makeItem(book, quantity));
return array;
},
[]
);
setItems(items);
initialized = true;
setLoading(false);
}
}
function addItemPrice(sum: number, item: Item): number {
return sum + itemPrice(item);
}
function isValidForCheckout(item: Item): boolean {
return item.quantity > 0 && itemIsValid(item);
}
function pushValidItemJson(array: ItemJson[], item: Item): ItemJson[] {
if (itemIsValid(item)) array.push(itemToJson(item));
return array;
}
export { createCartStore, itemPrice, itemIsValid };
export type { CartStore, CartStorage, Item };