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);
}
}
Related
I am trying to sum values from a report in GoogleAdsScript.
The report has to be segmented by campaignName, because of filter criteria.
The results should show aggregated values for IDs that exist in multiple campaigns.
I have managed to transform the report into an array and group by ID.
The last step would be to sum the values for each ID, as the GroupBy function I am using is not doing this.
Here's what I got so far:
function main() {
var report = generateReport();
Logger.log(groupBy(reportArray, "Id"));
}
function generateReport() {
var report;
var accountSelector = MccApp.accounts()
.withIds(['123-456-7890']);
var accountIterator = accountSelector.get();
while (accountIterator.hasNext()) {
var account = accountIterator.next();
MccApp.select(account);
report = AdsApp.report('SELECT segments.product_item_id, metrics.cost_micros, metrics.conversions_value, campaign.name, metrics.conversions, segments.product_custom_attribute4, segments.product_custom_attribute3, segments.product_custom_attribute2, segments.product_custom_attribute1 FROM shopping_performance_view WHERE campaign.name REGEXP_MATCH ".*_PPF_.*" AND campaign.name NOT REGEXP_MATCH ".*_PPF_Y.*" AND metrics.cost_micros > 50000000 AND segments.date DURING LAST_30_DAYS ORDER BY segments.product_item_id ASC');
}
return report;
}
function formatMicros(value) {
const micros = parseFloat(value / 1000000).toFixed(2);
return `${micros}`;
}
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
function reportToArray (report){
var array = [];
var rows = report.rows();
while (rows.hasNext()) {
//Relevante Variablen erstellen
var row = rows.next();
var campaignName = row["campaign.name"];
var offerId = row["segments.product_item_id"];
var conversionValue = row["metrics.conversions_value"];
var cost = formatMicros(row["metrics.cost_micros"]);
var conversions = row["metrics.conversions"];
var rowObject = {Kampagne:campaignName, Id:offerId, ConversionValue:conversionValue, Cost:cost, Converisons:conversions};
array.push(rowObject);
}
return array;
}
The result from the Logger.log look like this if the IDs are only present in one campaign:
{12345=[{Kampagne=SampleCampaignName1, Id=12345, Cost=84.68, Converisons=2.365506, ConversionValue=101.07449979}],
23456=[{Kampagne=SampleCampaignName1, Converisons=15.14796, Id=23456, ConversionValue=730.58781899, Cost=120.72}],
34567=[{ConversionValue=1185.87613113, Cost=108.33, Kampagne=SampleCampaignName1, Id=34567, Converisons=7.782904}]
And like this, if they are present in multiple campaigns:
45678=[{Kampagne=samplecampaignName1, Converisons=0.0, ConversionValue=0.0, Id=45678, Cost=65.73}, {ConversionValue=2091.72, Cost=77.34, Converisons=4.0, Id=45678, Kampagne=samplecampaignName2}]
How do I sum the values for Cost/ConversionValue/Conversions in this second Case?
Any help is greatly appreciated.
Kind Regards,
Jan
Sorry if I misunderstood the task.
var newArr = [];
class Kampagne {
constructor(Id, ConversionValue, Converisons, Cost) {
this.Id = Id;
this.ConversionValue = ConversionValue;
this.Converisons = Converisons;
this.Cost = Cost;
}};
var array = [
{Kampagne:'samplecampaignName1', Converisons:3.0, ConversionValue:0.0, Id:257680, Cost:65.73},
{ConversionValue:2091.72, Cost:77.34, Converisons:4.0, Id:257680, Kampagne:'samplecampaignName2'},
{ConversionValue:100, Cost:32.04, Converisons:1.0, Id:257681, Kampagne:'samplecampaignName3'}
];
array.forEach(function(element, idx){
let res = newArr.find((e) => e.Id == element.Id);
if(res==undefined) {
newArr.push(new Kampagne(element.Id, element.ConversionValue, element.Converisons, element.Cost));
} else {
res.ConversionValue += element.ConversionValue;
res.Converisons += element.Converisons;
res.Cost += element.Cost;
}
});
console.log(newArr);
New to JS and trying to create a simple shopping cart using only vanilla JS. I have an item with details and an image that populates on a shopping cart page. I need to have a delete button that allows items to be removed individually from the shopping cart page. Below is the snippet of code I'm having trouble with:
function deleteProduct(i) {
alert('i : ' + i)
productArr2.splice(i,1)
console.log(productArr2)}
And below is the full JS code in case it would be helpful for debugging. Any help is appreciated!:
//Global Variables
var quantity = "";
var glazes = "";
var img = "";
var addItem = "";
//Changes price when quantity is selected
function priceCounter(){
var price = document.getElementById("price-details");
price.innerHTML = document.getElementById("quantity").value;
}
function setImage(select){
var image = document.getElementsByName("image-swap")[0];
image.src = select.options[select.selectedIndex].value;
}
function items(title, quantity, glaze, price, img){
this.title = title;
this.quantity = quantity;
this.glaze = glaze;
this.price = price;
this.img = img;
}
//Add to Cart Functionality
function addToCart() {
var quantityCount = document.getElementById("quantityCount");
quantityCount.innerText = document.getElementById("quantity").value;
document.getElementById("quantityCount").style.visibility = "visible";
title = document.getElementsByClassName("productTitle");
quantity = document.getElementById("quantity").value;
glazing = document.getElementById("glazing").value;
price = document.getElementById("quantity").value;
img = "images/blackberry-bag.png"
addItem = new items(title, quantity, glazing, price, img);
window.localStorage.setItem(localStorageCount, JSON.stringify(addItem));
// localStorageCount += 1;
}
//creates array to hold bag items
var productArr = []
var productArr2 = []
class Product {
constructor(quantity, glaze) {
this.quantity = quantity
this.glaze = glaze
}
}
function addToCart() {
var quantity = document.getElementById('quantity').value
var glaze = document.getElementById('glaze').value
var bun = new Product(quantity, glaze)
productArr.push(bun)
updateCartNumber(productArr.length)
}
function goToCheckoutPage() {
alert("taking you to your cart")
localStorage.setItem('order', JSON.stringify(productArr))
window.location.replace("cart.html")
}
function checkoutPageLoaded() {
var loadedProductArr = localStorage.getItem('order')
var productArr2 = JSON.parse(loadedProductArr)
console.log(productArr2)
var cart = document.getElementById("cart")
for(var i = 0; i < productArr2.length; i++) {
var cinbun = productArr2[i]
var cinbunGlaze = cinbun.glaze
var cinbunQuantity = cinbun.quantity
cart.innerHTML += "<div class='cart-items'> Flavor: Pumpkin Spice Glaze: <img src="+ cinbunGlaze +"> Price: "+ cinbunQuantity +"</div>"
cart.innerHTML += "<span onclick= 'deleteProduct(" + i + ")'> Delete </span>"
}
}
function saveEdits() {
localStorage.setItem('order', JSON.stringify(productArr2))
}
function deleteProduct(i) {
alert('i : ' + i)
productArr2.splice(i,1)
console.log(productArr2)
}
function updateCartNumber(num) {
var cartCount = document.getElementById('quantityCount')
cartCount.innerHTML = num
}
// food object
var food1 = {
// returns food ingredients.
getIngredients: function() {
let ingredients = ["pepper", "salt", "crayfish"];
return ingredients;
}
}
var food2 = {
// returns food ingredients.
getIngredients: function() {
let ingredients = ["pepper", "maggi", "oil"];
return ingredients;
}
}
var food3 = {
// returns food ingredients.
getIngredients: function() {
let ingredients = ["inzu", "ogiri", "crayfish"];
return ingredients;
}
}
var foods = [food1, food2, food3];
var index = 2;
var getMyFoodIngredients = (function(){
let foodIngredients = foods[index].getIngredients();
return (index)=>{
foodIngredients = foods[index].getIngredients();
return foodIngredients;}
})();
function removeIngredient(){
let foodIngredients = getMyFoodIngredients(index);
foodIngredients.pop();
console.log(foodIngredients)
}
for (var x = 0; x < 3; x++)
removeIngredient();
The problem with this approach is that since am using an immediately invoking function(IIFE) the foodIngredients is been initialized once but i want the index of foods[] to be dynamically initialized and also form a closure
So how do i pass an argument to dynamically change the foods[] ingredient
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to create a simple shopping cart using javascript and prototypes.
Just a simple console app.
I want to call myBasket.prototype.addItems to add items in the inventory[] and similarly I would want to call myBasket.prototype.addQuantity and myBasket.prototype.totalAmount to increase the quantity of an item and sum the total amount respectively.
Where I am stuck is how do I call myBasket.prototype.addItems to do the needful? This is where I am stuck.
var inventory =
[
{ name: "apples", price: 19.95, quantity: 50 },
{ name: "oranges", price: 20.99, quantity: 40 },
{ name: "pineapples", price: 40.00, quantity: 60 },
{ name: "lemons", price: 10.12, quantity: 100 }
]
function myBasket(name, price, quantity){
this.name = name;
this.price = price,
this.quantity = quantity;
items.push(this);
}
myBasket.prototype.addItems = function(){
console.log('items added to cart')
}
myBasket.prototype.addQuantity = function(){
console.log('item quantity added to cart')
}
myBasket.prototype.totalAmount = function(){
console.log('Total amount is');
var total = this.price * this.quantity;
}
// newItem.prototype = Object.create(myBasket.prototype);
var newItem = [];
newItem = new myBasket({name:'milk', price:80,quantity: 2});
newItem.push(this.items);
console.log('new item(s) added', items);
var checkoutAmount = new myBasket();
console.log('checkout amount');
No, since you are new to OOP, think it this way. Every thing is an object.
So in your case, you should have class Item and class Basket you should also have a way to add and remove items from your basket.
See the code snippet bellow
class Item{
constructor(name,price,quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
}
class Basket {
constructor() {
this.items = []
}
addItem(item){
this.items.push(item)
}
}
let items = [
new Item("apples",40,20),
new Item("lemons",32,38),
new Item("mangos",44,67),
new Item("pineapples",32,88)
]
let basket = new Basket()
let market = document.getElementById("market")
let s = items.map((item,id)=>"<button onClick=addItem("+id+")>Add "+item.name+"</button>").join("")
market.innerHTML = s
function addItem(id) {
basket.addItem(items[id])
showBasket()
}
function showBasket() {
let cart = document.getElementById("items")
let s = basket.items.map((item,id)=>"<span style='margin: 5px'>"+item.name+"</span>").join("")
cart.innerHTML = s
}
<fieldset>
<legend>Basket</legend>
<div id="items"></div>
</fieldset>
<div id="market"></div>
Hope that answers your question
Since the question was edited and added to use prototypes, I am going to once more produce an elaboration using function prototypes
function Item(name,price,quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
function Basket() {
this.items = []
}
Basket.prototype.addItem = function(item) {
this.items.push(item);
}
let items = [
new Item("apples",40,20),
new Item("lemons",32,38),
new Item("mangos",44,67),
new Item("pineapples",32,88)
]
let basket = new Basket()
let market = document.getElementById("market")
let s = items.map((item,id)=>"<button onClick=addItem("+id+")>Add "+item.name+"</button>").join("")
market.innerHTML = s
function addItem(id) {
basket.addItem(items[id])
showBasket()
}
function showBasket() {
let cart = document.getElementById("items")
let s = basket.items.map((item,id)=>"<span style='margin: 5px'>"+item.name+"</span>").join("")
cart.innerHTML = s
}
<fieldset>
<legend>Basket</legend>
<div id=items></div>
</fieldset>
<div id=market></div>
To add items to an array, use push():
function myBasket(name, price, quantity){
this.name = name;
this.price = price,
this.quantity = quantity;
items.push(this);
}
I am attempting to create a simple program for practice that has a Store constructor which takes in an inventoryList array, an InventoryItem constructor that creates an object of each item to be stored within the inventoryList array. I want to add a method to the InventoryItem list that will take a number and add it to each item within the list. Below is my code:
var Store = function(inventory){
this.inventory = inventory;
}
var InventoryItem = function(cost, color, size){
this.cost = cost;
this.color = color;
this.size = size;
}
//create each inventory item as an object
var lamp = new InventoryItem(40.00, 'blue', 'small');
var throwPillow = new InventoryItem(25.00, 'yellow', 'medium');
var sconce = new InventoryItem( 18.00, 'gold', 'large');
var candles = new InventoryItem(10.00, 'white', 'small');
var curtains = new InventoryItem(30.00, 'purple', 'large');
//store inventory items into an inventory object
var inventorylist = [lamp, throwPillow, sconce, candles, curtains];
// add number of items to each item
InventoryItem.prototype.howMany = function(num){
function addCount(inventorylist){
for(var i = 0; i < inventorylist.length; i++){
inventorylist[i].howMany = num;
}
}
}
//store inventory within a store
var deannaStore = new Store(inventorylist);
var dionStore = new Store(inventorylist);
var mikeStore = new Store(inventorylist);
I am running into an issue when I attempt add a number to an item within the list
example: dionStore.howMany(15)
this gives me the error: Uncaught TypeError: dionStore.howMany is not a function
Any help would be greatly appreciated preferably with a detailed explanation of why this doesn't work.
The problem is that the method howMany is defined for InventoryItem objects, but you try to call it to dionStore object which is a Store.
Can you please describe what you want to achieve?
EDIT1 :
Maybe add the howMany method to Store, like Lashane mentions, which will create a quantity property to each InvetoryItem in its array
Store.prototype.howMany = function(num){
function addCount(inventorylist){
for(var i = 0; i < inventorylist.length; i++){
inventorylist[i].quantity = num;
}
}
}
EDIT2 :
In this case you will need a method in InventoryItem to set the quantity and another in Store to return the total quantity
Store.prototype.howMany = function(){
var totalQuantity = 0;
for(var i = 0; i < inventorylist.length; i++){
var item = inventorylist[i];
if (item.hasOwnProperty('quantity')) {
totalQuantity += item.quantity;
}
}
return totalQuantity;
}
InventoryItem.prototype.addQuantity = function(quantity) {
if (this.hasOwnProperty('quantity')) {
this.quantity += quantity;
} else {
this.quantity = quantity;
}
}
var Store = function(inventory) {
this.inventory = inventory;
}
Store.prototype.howMany = function() {
var totalQuantity = 0;
for (var i = 0; i < inventorylist.length; i++) {
var item = inventorylist[i];
if (item.hasOwnProperty('quantity')) {
totalQuantity += item.quantity;
}
}
return totalQuantity;
}
var InventoryItem = function(cost, color, size) {
this.cost = cost;
this.color = color;
this.size = size;
}
InventoryItem.prototype.addQuantity = function(qunatity) {
if (this.hasOwnProperty('quantity')) {
this.quantity += qunatity;
} else {
this.quantity = qunatity;
}
}
//create each inventory item as an object
var lamp = new InventoryItem(40.00, 'blue', 'small');
var throwPillow = new InventoryItem(25.00, 'yellow', 'medium');
var sconce = new InventoryItem(18.00, 'gold', 'large');
var candles = new InventoryItem(10.00, 'white', 'small');
var curtains = new InventoryItem(30.00, 'purple', 'large');
//store inventory items into an inventory object
var inventorylist = [lamp, throwPillow, sconce, candles, curtains];
lamp.addQuantity(1);
throwPillow.addQuantity(2);
sconce.addQuantity(3);
candles.addQuantity(4);
curtains.addQuantity(5);
lamp.addQuantity(1);
//store inventory within a store
var deannaStore = new Store(inventorylist);
var dionStore = new Store(inventorylist);
var mikeStore = new Store(inventorylist);
document.getElementById('output').innerHTML = 'dionStore.howMany() = ' + dionStore.howMany();
<div id="output"></div>
Your prototype defines a function and does nothing. And it is on the wrong prototype. Are you looking for this?
Store.prototype.howMany = function(num){
for(var i = 0; i < this.inventory.length; i++){
this.inventory[i].howMany = num;
}
}