-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add module to read and write localStorage
- Loading branch information
1 parent
5f571a8
commit 8ef4aaa
Showing
1 changed file
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
export const storedData = (() => { | ||
if (!localStorage.getItem('cart')) localStorage.setItem('cart',JSON.stringify({})); | ||
if (!localStorage.getItem('favs')) localStorage.setItem('favs',JSON.stringify([])); | ||
|
||
const storedCart = JSON.parse(localStorage.cart); | ||
const storedFavs = JSON.parse(localStorage.favs); | ||
|
||
function getData() { | ||
return { | ||
storedCart, | ||
storedFavs, | ||
}; | ||
} | ||
|
||
function getCounts() { | ||
let cartCount = 0; | ||
let favsCount = 0; | ||
for (const item in storedCart) { | ||
cartCount += storedCart[item]; | ||
} | ||
favsCount = storedFavs.reduce((curr, next) => curr + next); | ||
|
||
return { | ||
cartCount, | ||
favsCount, | ||
} | ||
} | ||
|
||
function isFav(item) { | ||
return storedFavs.includes(item); | ||
} | ||
|
||
function addFav(item) { | ||
if (!storedFavs.includes(item)) storedFavs.push(item); | ||
|
||
localStorage.setItem('favs', JSON.stringify(storedFavs)); | ||
} | ||
|
||
function removeFav(item) { | ||
const itemIndex = storedFavs.indexOf(item); | ||
storedFavs.splice(itemIndex, 1); | ||
|
||
localStorage.setItem('favs', JSON.stringify(storedFavs)); | ||
} | ||
|
||
function amountInCart(item) { | ||
return storedCart[item] || 0; | ||
} | ||
|
||
function addToCart(item) { | ||
if (!storedCart[item]) storedCart[item] = 0; | ||
storedCart[item] += 1; | ||
|
||
localStorage.setItem('cart', JSON.stringify(storedCart)); | ||
} | ||
|
||
function removeFromCart(item) { | ||
storedCart[item] -= 1; | ||
if (storedCart[item] === 0) delete storedCart[item]; | ||
|
||
localStorage.setItem('cart', JSON.stringify(storedCart)); | ||
} | ||
|
||
|
||
|
||
return { | ||
getData, | ||
getCounts, | ||
isFav, | ||
addFav, | ||
removeFav, | ||
amountInCart, | ||
addToCart, | ||
removeFromCart, | ||
} | ||
})(); |