-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
66 lines (62 loc) · 1.75 KB
/
storage.js
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
/** @returns {Array<{id:number, quantity: number}>} */
function getProducts() {
return JSON.parse(localStorage.getItem('cart')) || [];
}
/** @returns {{id: number, quantity: 1} | null} */
function getProduct(id) {
const storage = JSON.parse(localStorage.getItem('cart'));
return storage.find(e => e.id == id);
}
/**
* @param {number} id
* @returns {{id: number, quantity: number} | null} updateProduct
*/
function addProduct(id) {
let storage = JSON.parse(localStorage.getItem('cart'));
const _product = { id, quantity: 1 };
if (storage) {
const existingProduct = storage.find(e => e.id == id);
if (existingProduct) {
existingProduct.quantity += 1;
} else {
storage.push(_product);
}
} else {
storage = [_product];
}
localStorage.setItem('cart', JSON.stringify(storage));
return getProduct(id);
}
/**
* @param {number} id
* @returns {{id: number, quantity: number} | null} updateProduct
*/
function removeProduct(id) {
let storage = JSON.parse(localStorage.getItem('cart'));
if (storage) {
const existingProduct = storage.find(e => e.id == id);
if (existingProduct) {
existingProduct.quantity -= 1;
if (existingProduct.quantity == 0) {
storage = storage.filter(e => e.id != id)
}
}
}
localStorage.setItem('cart', JSON.stringify(storage));
return getProduct(id);
}
/**
* @param {number} id
* @returns {{id: number, quantity: number} | null} updateProduct
*/
function deleteProduct(id) {
let storage = JSON.parse(localStorage.getItem('cart'));
if (storage) {
const existingProduct = storage.find(e => e.id == id);
if (existingProduct) {
storage = storage.filter(e => e.id != id)
}
}
localStorage.setItem('cart', JSON.stringify(storage));
return getProduct(id);
}