Creating a function in Javascript OOP - javascript

Converting function list into order so it is OOP.
Currently I've a class shoppingCart functionality.
Inside shoppingCart we have; save, load, remove, etc and than access it.
a) Is this written in OOP correctly
b) How do you access specific functions.
JS
var cart = [];
function shoppingCart() {
//var Item = function(title, description, price, image_url, count) {
this.newitem = function(title, description, price, image_url, count) {
this.title = title
this.description = description
this.price = price
this.image_url = image_url
this.count = count
}
//function addIteamToCart(title, description, price,image_url, count){
this.addNewitem = function addIteamToCart(title, description, price, image_url, count) {
for (var i in cart) {
console.log(cart);
if (cart[i].title === title) {
cart[i].count += count;
return;
}
}
var item = new Item(title, description, price, image_url, count);
console.log(item);
cart.push(item);
saveCart();
}
};
console.log(shoppingCart.newitem(sss,ddd,zzz,sss));

You need to create a ShoppingCart object:
var sc = new shoppingCart();
sc.newitem(sss, ddd, zzz, sss);
console.log(sc);
BTW, the cart variable should probably be local to the shoppingCart function, not a global variable. And then it should be passed as an argument to saveCart().

Related

Add same object to an array

I've created a shopping cart, and right now the the cart contains a single apple, a single orange, and the total prices.
How would I add a second "apple" without creating another object?
For example, I now would like to add 2 apples to the cart, so the price in the array gets updated, as well as the total amount.
module.exports = {
shoppingCart: function () {
//create empty cart array
theCart = [];
// create two seperate versions of the same kind of object using class method
class Fruits {
constructor(fruit, price) {
this.fruit = fruit;
this.price = price;
// this.quantity = price * 2;
}
}
let fruit1 = new Fruits('Apple', 4.95); // create new object. sets the value of this
let fruit2 = new Fruits('Orange', 3.99);
let fruit3 = new Fruits('Total amount', fruit1.price + fruit2.price);
// combine both fruits into an array
let bothFruits = [fruit1, fruit2, fruit3];
//add items to the cart
Array.prototype.push.apply(theCart, bothFruits);
//remove items from the cart by calling this function
function removeAllItems() {
if ((theCart.length = !0)) {
theCart = [];
}
}
//removeAllItems();
console.log(theCart);
},
};
You may try to add the quantity also. Please try the following code:
module.exports = {
shoppingCart: function () {
//create empty cart array
theCart = [];
// create two seperate versions of the same kind of object using class method
class Fruits {
constructor(fruit, price, quantity) {
this.fruit = fruit;
this.quantity = quantity;
this.price = price * quantity;
}
}
let fruit1 = new Fruits("Apple", 4.95, 2); // create new object. sets the value of this
let fruit2 = new Fruits("Orange", 3.99, 1);
let fruit3 = new Fruits("Total amount", fruit1.price + fruit2.price);
// combine both fruits into an array
let bothFruits = [fruit1, fruit2, fruit3];
//add items to the cart
Array.prototype.push.apply(theCart, bothFruits);
//remove items from the cart by calling this function
function removeAllItems() {
if (theCart.length = !0) {
theCart = [];
}
}
//removeAllItems();
console.log(theCart);
}
}
You can try this code:
class Fruits {
constructor() {
this.items = [];
this.totals = 0;
}
calculateTotals() {
this.totals = 0;
this.items.forEach(item => {
let price = item.price;
let quantity = item.quantity;
let amount = price * quantity;
this.totals += amount;
});
}
addToCart(fruit, price, quantity) {
let obj = { fruit, price, quantity }
this.items.push(obj);
this.calculateTotals();
}
get cart() {
return { items: this.items, totals: this.totals }
}
}
const fruitsCart = new Fruits();
fruitsCart.addToCart("Apple", 10.5, 2);
fruitsCart.addToCart("Orang", 15, 1);
const cart = fruitsCart.cart;
this now adds the total amount in a separate variable
module.exports = {
shoppingCart: function () {
//create empty cart array
theCart = [];
// create two seperate versions of the same kind of object using class method
class Fruits {
constructor(fruit, price, quantity) {
this.fruit = fruit;
this.quantity = quantity;
this.price = price * quantity;
}
}
let fruit1 = new Fruits("Apple", 4.95, 2); // create new object. sets the value of this
let fruit2 = new Fruits("Orange", 3.99, 1);
//let fruit3 = new Fruits("Total amount", fruit1.price * fruit2.price);
// combine both fruits into an array
let bothFruits = [fruit1, fruit2];
//add items to the cart
Array.prototype.push.apply(theCart, bothFruits);
let total = fruit1.price + fruit2.price;
//remove items from the cart by calling this function
function removeAllItems() {
if (theCart.length = !0) {
theCart = [];
}
}
//removeAllItems();
console.log(theCart, total);
}
}

Shopping Cart Items JS

I'm trying to find out how to add a product to my cart once the 'add to cart' button is clicked, but since my cart and products are on separate html pages the console giving me this error
here is the JS for the product pages
var addToCartButtons = document.getElementsByClassName('cta')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
// Add Item to cart
function addToCartClicked(event) {
var button = event.target
var showcaseItem = button.parentElement.parentElement
var title = showcaseItem.getElementsByClassName('pp-title')[0].innerText
var price = showcaseItem.getElementsByClassName('pp-price')[0].innerText
var imgSrc = showcaseItem.getElementsByClassName('pp-img')[0].src
console.log(title, price, imgSrc)
addItemToCart(title, price, imgSrc)
}
function addItemToCart(title, price, imgSrc) {
var cartRow = document.createElement('div')
cartRow.innerText = title + price
var cartItems = document.getElementsByClassName('all-cart-items')[0]
cartItems.append(cartRow)
}
I believe it's because the element with the class 'all-cart-items' is on the cart markup and not the product page but I don't how to target that page with code. Would I need to use php?
I can also attach the html markups for both pages if necessary!
I have make a sample code using localstorage for adding item to car
var addToCartButtons = document.getElementsByClassName('cta')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
// Add Item to cart
function addToCartClicked(event) {
var button = event.target
var showcaseItem = button.parentElement.parentElement
var title = showcaseItem.getElementsByClassName('pp-title')[0].innerText
var price = showcaseItem.getElementsByClassName('pp-price')[0].innerText
var imgSrc = showcaseItem.getElementsByClassName('pp-img')[0].src
console.log(title, price, imgSrc)
addItemToCart(title, price, imgSrc)
}
function addItemToCart(title, price, imgSrc) {
var cartRow = document.createElement('div')
cartRow.innerText = title + price
var cartItems = document.getElementsByClassName('all-cart-items')[0]
cartItems.append(cartRow);
var cart = JSON.parse(localStorage.getItem("cartItemsr"));
if(cart != null && cart.length > 0){
cart({title: title, price: price, img: imgSrc});
}else{
cart = [{title: title, price: price, img: imgSrc}];
}
localStorage.setItem("cartItemsr", JSON.stringify((cart));
}
To retire the items in another page
var cart = JSON.parse(localStorage.getItem("cartItemsr"));
if(cart != null && cart.length > 0){
for (var i = 0; i < cart.length; i++) {
console.log("row", cart[I].title, cart[I].price, cart[I].img)
}
}
Frankly, this demands for some state management libraries or server side rendering languages like PHP. Yes, you would definitely need to save cart info, in the server, so I am sure you would have thought of that. However, to answer to the point,
you can store all the products in localStorage by doing JSON.stringify and in the cart page listen to the storage event and then do JSON.parse and save the info.
Do the below in product page
const list = JSON.parse(localStorage.getItem('productList'));
list.push(newItem)
localStorage.setItem('productList',JSON.stringify(list));
Do the below in cart page
window.addEventListener('storage', () => {
// When local storage changes, dump the list to
// the console.
console.log(JSON.parse(window.localStorage.getItem('productList')));
});

Object Constructors

I have a problem with creating a new Object in the constructor
My Aim is to take the user input and from that create a new object and push into an array using the constructor.
The problem is that when I try to fill the new input to create a new object it just replaced the old one with undefined values.
MY code :
let Book = document.querySelector("#one");
let Author = document.querySelector("#two");
let Year = document.querySelector("#three");
let Btn = document.querySelector("button");
Btn.addEventListener("click", () => {
Book = Book.value;
Author = Author.value;
Year = Year.value;
let myLibrary = [];
function newBook(name, author, year) {
this.name = name;
this.author = author;
this.year = year;
}
function addBookToLibrary(book, author, year) {
const Books = new newBook(book, author, year);
myLibrary.push(Books);
}
addBookToLibrary(Book, Author, Year);
console.log(myLibrary);
});
let Book = document.querySelector("#one");
let Author = document.querySelector("#two");
let Year = document.querySelector("#three");
let Btn = document.querySelector("button");
let myLibrary = [];
Btn.addEventListener("click", () => {
function newBook(name, author, year) {
this.name = name;
this.author = author;
this.year = year;
}
function addBookToLibrary(book, author, year) {
const Books = new newBook(book, author, year);
myLibrary.push(Books);
}
addBookToLibrary(Book.value, Author.value, Year.value);
console.log(myLibrary);
});
There are two mistakes in above code:
You are using local state of let myLibrary = []; which will be created on every click. It should be moved to a higher level so that on every click the value added can be preserved.
You are using same name of variables inside your function, which are overriding the Dom reference.

How do I add increment to two specific properties of a class?

Here are my instructions, I am having issues with getting two properties 'numberOfLikes' and 'comments' to use increment to adjust the amount of likes and comments. I don't know if I should use a for loop or if I just need the increment operator. I'm new to coding and apologize in advance.
/*
In the space below, add to the existing skeleton of a Tweet class.
A tweet should have a (dynamic) author, content, timeStamp, numberOfLikes, and comments.
A tweet should be able to increment the numberOfLikes and add to the list of comments.
Create several instances of your Tweet and log them to the console. Make sure the
tweet object instances behave as expected.
*/
class Tweet {
constructor(author, content, timeStamp, numberOfLikes, comments) {
this.author = author;
this.content = content;
this.timeStamp = timeStamp;
this.numberOfLikes = numberOfLikes;
this.comments = comments;
}
};
//This is code I was playing around with, doesn't work
this.add = function(numberOfLikes){
for(i = 0; i < numberOfLikes.length; i++){
console.log("You have " + numberOfLikes + " likes");
}
}
this.add = function(comments) {
for(i = 0; i < comments.length; i++) {
console.log("You have " + comments + " comments");
}
}
var tweet1 = new Tweet("Rihanna", "Fenty Beauty", "12:31 A.M.", 120193, 6782);
Thanks in advance!
A tweet should be able to increment the numberOfLikes
This should be a function to increase the numberOfLikes.
and add to the list of comments.
comments is probably an array. This means that you need a function to add a comment, to the list of your comments.
class Tweet {
constructor(author, content, timeStamp, numberOfLikes, comments) {
this.author = author;
this.content = content;
this.timeStamp = timeStamp;
this.numberOfLikes = numberOfLikes;
this.comments = comments;
}
increaseNumberOfLikes() {
this.numberOfLikes++
}
addComment(commentText) {
this.comments.push(commentText)
}
};
let tweet1 = new Tweet("The Weekend", "Some content", "15:31 P.M.", 9800, ["so cool", "do it again"])
tweet1.increaseNumberOfLikes()
tweet1.addComment("Great Song!")
console.log(tweet1)
You should create more tweets like above.
You can create functions that use += and array#push to increment numbers and add values to arrays.
Incrementing tweets:
incrementLikes(increment = 1) {
this.numberOfLikes += increment
}
Adding a comment to the array:
addComment(comment) {
this.comments.push(comment)
}
I also noticed that in your post you mentioned that this.comments was a list. So I made that change when initializing the class.
new Tweet("Rihanna", "Fenty Beauty", "12:31 A.M.", 120193, ["amazing", "wow"]);
Demo:
class Tweet {
constructor(author, content, timeStamp, numberOfLikes, comments) {
this.author = author;
this.content = content;
this.timeStamp = timeStamp;
this.numberOfLikes = numberOfLikes;
this.comments = comments;
}
incrementLikes(increment = 1) {
this.numberOfLikes += increment
}
addComment(comment) {
this.comments.push(comment)
}
};
var tweet1 = new Tweet("Rihanna", "Fenty Beauty", "12:31 A.M.", 120193, ["amazing", "wow"]);
tweet1.incrementLikes()
console.log(tweet1.numberOfLikes)
tweet1.incrementLikes()
console.log(tweet1.numberOfLikes)
tweet1.addComment("This is a comment")
console.log(tweet1.comments)
Within the class body you need to define prototypal functions like this:
class Tweet {
constructor(author, content, timeStamp, numberOfLikes, comments) {
this.author = author;
this.content = content;
this.timeStamp = timeStamp;
this.numberOfLikes = numberOfLikes;
this.comments = comments;
}
like() {
this.numberOfLikes++;
}
comment(comment) {
this.comments.push(comment);
}
}
const tweet1 = new Tweet("Rihanna", "Fenty Beauty", "12:31 A.M.", 120193, ["I hate I hate know-it-alls"]);
console.log(tweet1.numberOfLikes);
tweet1.like();
tweet1.like();
console.log(tweet1.numberOfLikes);
console.log(tweet1.comments);
tweet1.comment("I love you Rihanna!!")
console.log(tweet1.comments);
.as-console-wrapper { min-height: 100%!important; top: 0; }
This should work. You need to put the function definitions inside the class definition. I also modified the function names, because they conflict with each other.
class Tweet {
constructor(author, content, timeStamp, numberOfLikes, comments) {
this.author = author;
this.content = content;
this.timeStamp = timeStamp;
this.numberOfLikes = numberOfLikes;
this.comments = comments;
}
addLikes(numberOfLikes){
this.numberOfLikes += numberOfLikes
}
addComments(comments) {
this.comments += comments
}
};
// Initial tweet instance
var tweet1 = new Tweet("Rihanna", "Fenty Beauty", "12:31 A.M.", 120193, 6782);
// Call modifiers
tweet1.addLikes(5)
tweet1.addComments(7)
// Check the variables were modified
console.log(tweet1.numberOfLikes)
console.log(tweet1.comments)

Function not returning enough object parameters

I have a function that I have modified from some other code, and I am confused. With the 'else if' it seems that the 'Income' object only returns three attributes, rather than the four I need (I can return the value parameter, or I can use the value parameter in a calculation to a different value, but I can't capture both).
return {
addItem: function(type, des, val, price){
var newItem, ID;
if(data.allItems[type].length > 0){
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
}else{
ID = 0;
}
if (type === 'exp'){
newItem = new Expense(ID, des, val);
}else if (type === 'inc'){
var ben = val * price;
newItem = new Income(ID, des, val, ben);
}
data.allItems[type].push(newItem);
return newItem;
},
I think my problem lies with this function, but as I say, I am now very confused. Is there an obvious problem with it?
Edit: this is the Income function constructor:
var Income = function(id, description, value, price){
this.id = id;
this.description = description;
this.value = value;
this.price = price;
this.ben = ben;
};
If you want to track ben, you can add it to the constructor args.
var Income = function(id, description, value, price, ben){
And add price when you instantiate a new Income object.
newItem = new Income(ID, des, val, price, ben);

Categories