Skip to content

Commit

Permalink
add module to read and write localStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
HectorVilas committed May 2, 2023
1 parent 5f571a8 commit 8ef4aaa
Showing 1 changed file with 76 additions and 0 deletions.
76 changes: 76 additions & 0 deletions modules/storedData.js
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,
}
})();

0 comments on commit 8ef4aaa

Please sign in to comment.