Replacing old values in array with new ones on button click - javascript

So I am creating a web app that uses the BLE web api. I made it so that when you press the scan button it scans for bluetooth devices and filters out all the ones that are not ESP's. Then it calculates the distance and pushes it into an array. As it is now if you press scan multiple times the array jsut gets longer and longer because of the "push". However i want it to replace old values with the new values when you press scan again. so that the array length stay 3.
import * as trilateration from './trilateration.js';
import context from './context.js';
const beaconMapping = {
'ESP32_1': 0,
'ESP32_2': 1,
'ESP32_3': 2,
}
const DISTANCE_SCALAR = 1;
console.log("Init");
const devices = [];
const ids = [];
const beaconuuid = [];
const distances = [];
const SCAN_TIME = 10000;
//add beacons to trilatertion;
trilateration.addBeacon(0, trilateration.vector(10.1, 7.0));
trilateration.addBeacon(1, trilateration.vector(0, 0));
trilateration.addBeacon(2, trilateration.vector(10.1, 0));
document.getElementById("scan").onclick = scan;
async function scan() {
console.log("Scanning...");
let options = {
acceptAllAdvertisements: true,
acceptAllDevices: true,
};
try {
log("Requesting Bluetooth Scan with options: " + JSON.stringify(options));
const scan = await navigator.bluetooth.requestLEScan(options);
log("Scan started with:");
log(" acceptAllAdvertisements: " + scan.acceptAllAdvertisements);
log(" active: " + scan.active);
log(" keepRepeatedDevices: " + scan.keepRepeatedDevices);
log(" filters: " + JSON.stringify(scan.filters));
navigator.bluetooth.addEventListener("advertisementreceived", (event) => {
let name = event.device.name;
if (name && name.startsWith("ESP32") && !ids.includes(event.device.id)) {
console.log("Found");
//console.log(event);
//add to device list if name starts with ESP32
console.log("adding");
const obj = {
device: event.device,
uuids: event.uuids,
rssi: event.rssi,
tx: event.txPower,
distance: calculateDistance(event.rssi, event.txPower) * DISTANCE_SCALAR,
};
console.log(obj);
console.log(obj.tx, obj.rssi, obj.distance, name);
devices.push(obj);
ids.push(event.device.id);
const beaconIndex = beaconMapping[event.device.name];
if (beaconIndex !== undefined) {
distances.push(obj.distance);
trilateration.setDistance(beaconIndex, obj.distance);
} else {
console.error("Name not found in mapping");
}
if (distances.length > 2) {
var pos = trilateration.calculatePosition();
console.log(pos);
console.log("Distqnces qrr length", distances.length)
console.log("X: " + pos.x + "; Y: " + pos.y);
context.fillRect(pos.x * 100, pos.y * 100, 20, 20);
}
showBeaconInfo(obj);
}
/* log('Advertisement received.');
log(' Device Name: ' + event.device.name);
log(' Device ID: ' + event.device.id);
log(' RSSI: ' + event.rssi);
log(' TX Power: ' + event.txPower);
log(' UUIDs: ' + event.uuids); */
});
setTimeout(stopScan, SCAN_TIME);
function stopScan() {
console.log("List of all devices detected:");
console.log(devices);
console.log(ids)
console.log(beaconuuid);
console.log(distances)
log("Stopping scan...");
scan.stop();
log("Stopped. scan.active = " + scan.active);
}
} catch (error) {
log("Argh! " + error);
}
}

You can either go with the object approach and use the uuid as the keys which will replace whenever you add the same uuid to the object again.
If you want to go with the array approach you can check whether an object with that uuid already exists and then overwrite that index.
Here's a general idea.
// This will return the index if the element exists or -1 if it doesn't exist
const index = array.findIndex(element => element.uuid === obj.uuid)
if (index === -1) {
array.push(obj)
} else {
array[index] = obj
}
And this will keep the array constrained to only unique elements.

Related

Changing an object variable is changing that variable for all similar objects in Javascript [duplicate]

This question already has answers here:
Javascript object members that are prototyped as arrays become shared by all class instances
(3 answers)
Crockford's Prototypal inheritance - Issues with nested objects
(3 answers)
Closed 11 months ago.
I am using a player object (playerObject) that has properties and is changed constantly. I initialize with 4 playerObjects with their own properties and name.
This is a clone of the board game monopoly.
When a player lands on a property and checks function canIBuy() and they buy it, it purchases that property for every player. Why is this happening?
Posting all the JS code in case there is something i am missing, although this is the broken part.
Player lands on space
checks isProperty()
if property, runs canIBuy()
buys it if its available and they have the cash
const logs = document.getElementById("logDiv")
const stats = document.getElementById("stats")
var player1,player2,player3,player4
var players = []
const availableNames = [
"dog", "battleship", "race car", "top hat", "cat", "penguin", "t-rex", "rubber ducky"
]
const spots = [
'Go','Mediterranean Avenue','Community Chest','Baltic Avenue','Income Tax','Reading Railroad','Oriental Avenue','Chance','Vermont Avenue','Connecticut Avenue','Jail / Just Visiting','St. Charles Place','Electric Company','States Avenue','Virginia Avenue','Pennsylvania Railroad','St. James Place','Community Chest','Tennessee Avenue','New York Avenue','Free Parking','Kentucky Avenue','Chance','Indiana Avenue','Illinois Avenue','B. & O. Railroad','Atlantic Avenue','Ventnor Avenue','Water Works','Marvin Gardens','Go To Jail','Pacific Avenue','North Carolina Avenue','Community Chest','Pennsylvania Avenue','Short Line','Chance','Park Place','Luxury Tax','Boardwalk'
]
// spots that can not be bought
const nonproperties = [
0,2,4,7,10,17,20,22,30,33,36,38
]
const spotPrices = [-1,60,-1,60,-1,200,100,-1,100,120,-1,140,150,140,160,200,180,-1,180,200,-1,220,-1,220,240,200,260,260,150,280,-1,300,300,-1,320,200,-1,350,-1,400]
const spotRents = [-1,2,-1,4,-1,-1,6,-1,6,8,-1,10,-1,10,12,-1,14,-1,14,16,-1,18,-1,18,20,-1,22,22,-1,22,-1,26,26,-1,-1,28,-1,35,-1,50];
function log(x) {
logs.innerHTML += "</br>" + x
}
const playerObject = {
name:undefined,
cash:1500,
owned:[],
currentSpot:0,
inJail:false,
getOutOfJailRolls:0,
init() {
log(bold(this.name) + " has joined the game!")
statRefresh()
},
move(r1,r2) {
let newSpot = this.currentSpot+(r1+r2)
if (newSpot >= spots.length) {
newSpot = newSpot - spots.length
log(bold(this.name)+ " passed Go and collected $200")
this.cash += 200
}
log (bold(this.name) + " rolled: "+r1+" & "+r2)
log(bold(this.name) + " moved "+(r1+r2)+" spaces from "+spots[this.currentSpot]+" to "+spots[newSpot])
this.currentSpot = newSpot
if (isProperty(this.currentSpot)) {
canIBuy(this)
console.log("checking if "+this.name+" can buy "+spots[this.currentSpot])
}
statRefresh()
},
jail() {
this.currentSpot = 10 // JAIL SPOT
this.inJail = true
log(bold(this.name)+" has rolled their third set of doubles and went straight to jail! ")
log("</br>")
statRefresh()
},
purchase() {
this.owned.push(this.currentSpot)
this.cash -= spotPrices[this.currentSpot]
}
}
function initalizeGame() {
player1 = Object.create(playerObject)
player1.name = availableNames[Math.floor(Math.random() * availableNames.length)]
availableNames.splice(availableNames.indexOf(player1.name), 1)
player1.init()
player2 = Object.create(playerObject)
player2.name = availableNames[Math.floor(Math.random() * availableNames.length)]
availableNames.splice(availableNames.indexOf(player2.name), 1)
player2.init()
player3 = Object.create(playerObject)
player3.name = availableNames[Math.floor(Math.random() * availableNames.length)]
availableNames.splice(availableNames.indexOf(player3.name), 1)
player3.init()
player4 = Object.create(playerObject)
player4.name = availableNames[Math.floor(Math.random() * availableNames.length)]
availableNames.splice(availableNames.indexOf(player4.name), 1)
player4.init()
log("<br/>")
players.push(player1,player2,player3,player4)
statRefresh()
}
document.getElementById("nextTurn").onclick = function() {
roll(player1)
roll(player2)
roll(player3)
roll(player4)
}
function roll(player) {
if (!player.inJail) {
let r1,r2
let consec = 0
let consecTimes = ["first", "second", "third"]
while (r1 == r2) {
r1 = Math.ceil(Math.random() * (6-1 + 1))
r2 = Math.ceil(Math.random() * (6-1 + 1))
if (r1 == r2) {
log("<strong>"+player.name + "</strong> rolled doubles for the " +consecTimes[consec]+" time.")
consec++
if (consec >= 3) {
return player.jail()
}
}
if (consec < 3) {
player.move(r1,r2)
}
}
log("<br/>")
} else {
if (player.cash > 1000000) {
log(bold(player.name)+ " paid to get out of jail. Rolling to move...")
player.inJail = false
roll(player)
} else {
r1 = Math.ceil(Math.random() * (6-1 + 1))
r2 = Math.ceil(Math.random() * (6-1 + 1))
log(bold(player.name) + " rolled a "+r1+" & "+r2+" in jail")
player.getOutOfJailRolls++
if (r1 == r2 || player.getOutOfJailRolls > 3) {
log(bold(player.name) + " has busted out of jail. Rolling to move...")
player.inJail = false
player.getOutOfJailRolls = 0
roll(player)
} else {
log(bold(player.name) + " is stuck in jail after rolling "+ r1+" & "+r2 +" ("+player.getOutOfJailRolls+"/3 tries)")
}
}
}
}
function bold(x) {
return "<strong>"+x+"</strong>"
}
function statRefresh() {
var t = document.createElement("table")
stats.innerHTML = ""
for (let i=0;i<players.length;i++) {
var r = t.insertRow(0)
var name = r.insertCell(0)
name.innerText = players[i].name
var cash = r.insertCell(1)
cash.innerText = "$"+players[i].cash
var spot = r.insertCell(2)
spot.innerText = spots[players[i].currentSpot]
var jail = r.insertCell(3)
jail.innerText = "Jailed:"+players[i].inJail
var prop = r.insertCell(4)
prop.innerText = players[i].owned
stats.append(t)
}
}
function isProperty(x) {
if (nonproperties.indexOf(x) == -1) {
return true
}
}
function canIBuy(x) {
//console.log("canibuy:"+x.name)
let alreadyPurchased = false
let purchasedBy
for (let i=0;i<players.length;i++) {
if (players[i].owned.indexOf(x.currentSpot) != -1) {
alreadyPurchased = true
purchasedBy = players[i]
log(spots[x.currentSpot]+" is already owned by "+purchasedBy.name)
}
}
if (alreadyPurchased) {
payRent(x, purchasedBy, x.currentSpot)
} else if (x.cash > spotPrices[x.currentSpot]) {
if (Math.floor(Math.random() * 9) + 1 <= 8) {
// buy it 80% of the time if you have the cash
log(bold(x.name) + " is buying "+spots[x.currentSpot] +" for $"+spotPrices[x.currentSpot])
console.log(x)
x.purchase()
console.log(players)
} else {
log(bold(x.name) + " decided not to buy "+spots[x.currentSpot])
}
}
}
function payRent(payer, payee, spot) {
let rent = spotPrices[spot]
if (payer.cash > rent) {
payer.cash -= rent
payee.cash += rent
log(bold(payer.name)+" paid " +payee.name+" $"+rent+" for rent at "+spots[spot])
}
}
initalizeGame()

Recursive java script function - out of control

The code below works. The code calls an API to get historical trades (100 trades each time pér pull). Because there is an limit - how many and how often im allowed to call the API - the structure is like recursive.
The flow is like this:
Get the current MAX tradeId - which is stored in the DB.
Now make a new PULL with startIndex = MaxId and a length of 100 (to pull 100 new trades).
FIRST when the callback function is called the main code continues and 100 new trades are pulled... ect. ect.
So...
The code SHOULD behave like - Psydo-code
var maxId = GetMaxIdFromDB();
Pull(maxId, 100, callback);
function callback(){
... do different stuff..
maxId += 100;
Pull(maxId, 100, callback);
}
The strange thing and my question is: How can the API function "getProductTrades " be called more than one time - where my cursor variable contains the SAME value - when it is incremented with 100 (or the number of valid data elements each time).
I'm talking/ref. especially to the following lines:
wl.debug("getProductTrades - cursor: " + cursor + " Limit: " + limit);
publicClient.getProductTrades({'after': cursor, 'limit': limit}, callback);
The insertQuery.InsertMatchMsgArrayToDB(allData); method calls another DB method which returns a promise.
You can see a screenshot of the issue here:
http://screencast.com/t/DH8rz3UxnyZ
The real code is here:
pullTradesBetween: function (minTradeId, maxTradeId) {
var wl = new WinLog();
var tradeCounter = 0;
try {
var WebSocketEmit = new WSemitter();
var startTime = new Date().toLocaleString();
var executeTradePullAgain = null;
wl.debug("REST API START: " + startTime);
var cursor;
var incrementedCursorWith = 0;
if ((maxTradeId - minTradeId) < 100) {
cursor = maxTradeId + 1;
}
else
cursor = minTradeId + 100;
var callback = function (err, response, data) {
if (executeTradePullAgain !== null)
clearTimeout(executeTradePullAgain);
if (err)
wl.info("Err: " + err);
var validData = [];
incrementedCursorWith = 0;
if (response == null)
wl.info("RESPONSE ER NULL");
if (data !== null) {
for (var i = data.length - 1; i >= 0; i--) {
var obj = data[i];
var tradeId = parseInt(obj.trade_id);
if (obj !== null && (minTradeId <= tradeId && tradeId <= maxTradeId)) {
validData.push(data[i]);
}
}
if (validData.length == 0) {
wl.debug("Contains 0 elements!");
}
else {
cursor = cursor + validData.length;
incrementedCursorWith = validData.length;
insertDataToDB(validData);
}
}
else
wl.debug("DATA IS NULL!");
wl.debug("cursor: " + cursor + " maxTradeId: " + maxTradeId);
var diffToMax = maxTradeId - (cursor - incrementedCursorWith);
if (diffToMax >= 100)
pullTrades(cursor, 100); // 100 is default
else if (diffToMax >= 0)
pullTrades(maxTradeId + 1, diffToMax + 1); // X = Only the last trades in the given series of trades
else {
wl.info("REST API START: " + startTime + " REST API DONE: " + new Date().toLocaleString());
WebSocketEmit.syncHistoricalDataDone();
}
};
function pullTrades(cursor, limit) {
tradeCounter += limit;
if(tradeCounter % 10000 == 0){
wl.info('Downloaded: ' + tradeCounter + ' trades via REST API (Total: ' + cursor + ')');
}
pullTradesAgainIfServerDoesNotRespond(cursor, limit);
wl.debug("getProductTrades - cursor: " + cursor + " Limit: " + limit);
publicClient.getProductTrades({'after': cursor, 'limit': limit}, callback);
}
function pullTradesAgainIfServerDoesNotRespond(cursor, limit) {
executeTradePullAgain = setTimeout(function () {
wl.debug('pullTradesAgainIfServerDoesNotRespond called!');
pullTrades(cursor, limit);
}, 30000);
}
// SAVE DATA IN DB!
function insertDataToDB(allData) {
insertQuery.InsertMatchMsgArrayToDB(allData);
}
wl.debug("pull trades: " + cursor);
pullTrades(cursor, 100);
}
catch(err){
wl.info('pullTradesBetween: ' + err);
} }};
It happens when you get no data out of getProductionTrades.
If the data returned is null, you will never reach the lines
cursor = cursor + validData.length;
incrementedCursorWith = validData.length;
but you still call
pullTrades(cursor, 100);
at the end. I don't know if it's intended or an actual error so i leave the solution (should be trivial now) up to you.
I try to simplify your code
pullTradesBetween: function (minTradeId, maxTradeId) {
var WebSocketEmit = new WSemitter(); // try-catch ?
var curr = (maxTradeId - minTradeId < 100) ? maxTradeId + 1 : minTradeId + 100;
// function always return data or infinite error-loop
function getProductTrades (after, limit, callback) {
// try-catch ?
publicClient.getProductTrades ({after, limit}, function(err, data) {
if (err) {
console.log(err);
return getTrades(after, limit, callback);
}
callback(null, data);
});
}
function onDataReady (err, data) {
if (err)
throw new Error('Impossible!');
if (!data || !(data instanceof Array))
return ... smth on empty data ...
var validData = data.filter(function(obj) {
return obj &&
minTradeId <= parseInt(obj.trade_id) &&
parseInt(obj.trade_id) <= maxTradeId;
}).reverse();
if (validData.length == 0)
return ... smth on empty data ...
insertDataToDB(validData);
curr += validData.length; // maybe +-1
var remaining = maxTradeId - curr;
if (remainig == 0) {
console.log('Done');
// try-catch ?
WebSocketEmit.syncHistoricalDataDone();
}
return (remaining >= 100) ?
getProductTrades(curr, 100, onDataReady) :
getProductTrades(maxTradeId + 1, remaining + 1, onDataReady); // ??
}
getProductTrades(curr, 100, onDataReady);
}

Why isn't my program assigning variables to the object, and then calculating from it?

This assignment is to take a pizza order and build one. Once the pizza is assembled, it should calculate the total cost of the pizza and spit out the total answer. I've played around on JsFiddle.net for two days now and can't figure out why it won't get past the interrogate function and move on to the calculate. I've entered in a couple alert statements here and there and still can't figure out what's going on. My best guess is either that 'myPizza' properties are not being assigned or that they are not being shared by the other functions. I know the second possibility could not be true because 'myPizza' is a global object with global properties.
recycle = true;
var ingrediants = ['pepperoni ', 'sausage ', 'avocado ', 'chicken ', 'mushrooms ', 'anchovies ', 'bacon ', 'pineapple ', 'beeswax '];
var toppings=[];
var i = -1;
var myPizza= {
size:"",
toppings:[],
stuffCrust:false,
sodaSide: false
};
var greeting = function () {
wantPizza = prompt("Hello! Welcome to Sean's Pizza Shack! Would you like to order a pizza?(Yes or No?)").toLowerCase();
if (wantPizza === 'yes') {
return true;
} else {
alert("Okay then, Get out of my pizza shop because I have customers waiting");
return false;
}
};
var interrogate = function () {
myPizza.size = prompt("Okay sir/Ma'am, Would you like a Small, Medium, Large, or extra Large?(XL)").toLowerCase();
myPizza.toppings = prompt("Alright! So what would you like on your " + myPizza.size + " pizza?" + " We have " + ingrediants).toLowerCase();
do {
i = i + 1;
myPizza.toppings+= toppings[i] =prompt(ingrediants + " Please type one ingrediant at a time to add to your pizza! or you may enter 'ALL' to add all toppings or press OK without entry to stop adding toppings").toLowerCase();
} while (toppings[i] !== "");
//LOOP TO DECIDE IF NEED TO PUSH ALL INGREDIENTS
for (k = 0; k <toppings.length; k++) {
if (toppings[k] === 'all') {
toppings = [];
toppings.push(ingrediants);
} else {
toppings.length -= 1; // IF NOT ALL INGREDIENTS, SUBTRACT '' FROM ADD INGREDIENTS //LOOP
}
}
alert("So you would like " + myPizza.toppings + " on your pizza!");
alert("Okay so i have a " + myPizza.size + " pizza, with " + myPizza.toppings + "!");
myPizza.stuffCrust = prompt("Do you want your pizza to have extra delicious stuffed cheesy crust?($4.00)").toLowerCase();
if(myPizza.stuffCrust==='yes') {
myPizza.stuffCrust=true;
}
myPizza.sodaSide = prompt("Would you like a 2 Liter soda with that for an extra $2.00?");
if(myPizza.sodaSide=== yes) {
myPizza.sodaSide=true;
}
alert(myPizza.sodaSide);
alert(myPizza.toppings);
alert(myPizza.stuffCrust);
alert(myPizza.toppings.length);
};
var up= {
total:0,
Sm:9.00,
Med:12.00,
Lrg: 15.00,
XL: 18.00,
Top: myPizza.toppings.length*1.00,
Stuff:4.00,
Soda: 2.00,
add: function(input) {
total+=input;
}
};
var calculate= function() {
switch(myPizza.size) {
case 'small': up.add(up.Sm);break;
case 'medium': up.add(up.Med);break;
case 'large': up.add(up.Lrg);break;
case 'XL': up.add(up.XL);break;
}
if(myPizza.toppings.length>0) {
up.add(up.Top);
} if (myPizza.stuffCrust) {
up.add(up.Stuff);
} if (myPizza.sodaSide) {
up.add(up.Soda);
}
alert("Okay, looks like your order comes to "+ up.total);
};
var main= function () {
if (greeting() === true) {
interrogate();
calculate();
}
};
main();
in the statement:
if(myPizza.sodaSide=== yes) {
myPizza.sodaSide=true;
}
you need to have yes in quotes:
if(myPizza.sodaSide=== 'yes') {
myPizza.sodaSide=true;
}

How to add the numeric values of properties of a nested array?

I'm trying to figure out how to make a function that adds the values of the elements chosen by the user and be able to display the results via prompt and console.log. Also, I'm wondering if there is a way to do it in which I don't need to specify the elements selected in order for the function to find within the code which elements were selected and execute the addition function. Because obviously if the list of options were longer I wouldn't want to have to make a new function for each potential combination of selections. As a side note, I guess the same problem would apply to the if statements, would switch statements be the most efficient way to tackle needs for "DRY" code in that instance?
My javascript code: Please assume that the user selects only the first elements of the nested arrays. Also, that term "one" is worth $8.
var selection = new Array (3);
selection[0] = new Array ('$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8');
selection[1] = new Array ('phone1', 'phone2', 'phone3');
selection[2] = new Array ('one', 'two', 'three');
function pickPhone () {
var yourPhone = prompt("pick phone: phone1: $1, phone2: $2, phone3: $3");
if (yourPhone == selection[1][0]) {
console.log(selection[1][0] + " will cost: " + selection[0][0]);
alert(selection[1][0] + " will cost: " + selection[0][0]);
pickTerm ();
} if (yourPhone == "phone2") {
alert(selection[1][1] + " will cost: " + selection[0][1]);
} if (yourPhone == "phone3") {
alert(selection[1][2] + " will cost: " + selection[0][2]);
}
}
function pickTerm () {
var yourTerm = prompt("pick term: one, two or three?");
if (yourTerm == selection[2][0]) {
alert("Your total so far is: ??");
}
}
pickPhone ();
Any help is greatly appreciated, thank you.
A solution that keeps your arrays
http://jsfiddle.net/OxyDesign/o10ezyun/
JS
var selection = new Array(3);
selection[0] = new Array(1,2,3,4,5,6,7,8);
selection[1] = new Array('phone1', 'phone2', 'phone3');
selection[2] = new Array('one', 'two', 'three');
var firstValue;
function pickPhone() {
var yourPhone = prompt("pick phone: phone1: $1, phone2: $2, phone3: $3"),
index = selection[1].indexOf(yourPhone);
if(!~index){
pickPhone();
}else{
firstValue = selection[0][index];
alert(selection[1][index] + " will cost: $" + firstValue);
pickTerm();
}
}
function pickTerm() {
var yourTerm = prompt("pick term: one, two or three?"),
index = selection[2].indexOf(yourTerm),
finalValue = '$'+(firstValue+selection[0][index]);
if(!~index){
pickTerm();
}else{
alert("Your total so far is: "+finalValue);
}
}
pickPhone();
I'am not sure what problem you are actually solving.
How long these lists are (phones, costs, etc)?
What type of mapping is set for those items?
For now I'd recommend to merge corresponding values in objects like this:
// item -> cost
var phones = [
{title: 'phone1', cost: '$1'},
{title: 'phone2', cost: '$2'},
{title: 'phone3', cost: '$3'}
],
terms = [
{title: 'one', cost: '$8'},
{title: 'two', cost: '$2'},
{title: 'three', cost: '$3'}
],
phonesListWithCosts = (function(list) {
return list.reduce(function(memo, item) {
return memo + item.title + ': ' + item.cost;
}, '');
}(phones)),
termsList = (function(list) {
return list.reduce(function(memo, item) {
return memo + ', ' + item.title;
}, '');
}(terms)),
findBy = function(array, property, value) {
return array.filter(function(item) {
return item[property] === value;
})[0];
},
getItem = function(list, promptMessage) {
var selectedItemTitle = prompt(promptMessage);
return findBy(list, 'title', selectedItemTitle);
},
getItemCost = function(item) {
return parseInt(item.cost.replace(/\D/g, ''), 10);
},
pickPhone = function() {
var selectedPhone = getItem(phones, 'pick phone: ' + phonesListWithCosts),
firstPhone = phones[0],
message;
if (selectedPhone) {
message = [selectedPhone.title, 'will cost:', selectedPhone.cost].join(' ');
console.log(message);
alert(message);
if (selectedPhone === firstPhone) {
pickTerm(getItemCost(selectedPhone));
}
}
},
pickTerm = function(accumCost) {
var selectedTerm = getItem(terms, 'pick term: ' + termsList),
totalCost,
message;
if (selectedTerm) {
totalCost = accumCost + getItemCost(selectedTerm);
message = 'Your total so far is: $' + totalCost;
alert(message);
}
};
pickPhone();
jsbin demo.

Javascript Functions, Uncaught syntax error, Unexpected token?

The following code is giving me an error in the chrome developer tools:
"uncaught syntax error- unexpected token"
Specifically, the Errors come up in the populate header function at
var notraw = JSON.parse(arrayraw)
and in the first if statement, at
parsed = JSON.parse(retrieved); //var test is now re-loaded!
These errors haven't come up in previous iterations. Does anyone know why?
// This statement should be ran on load, to populate the table
// if Statement to see whether to retrieve or create new
if (localStorage.getItem("Recipe") === null) { // if there was no array found
console.log("There was no array found. Setting new array...");
//Blank Unpopulated array
var blank = [
["Untitled Recipe", 0, 0]
];
// Insert Array into local storage
localStorage.setItem("Recipe", JSON.stringify(blank));
console.log(blank[0]);
} else {
console.log("The Item was retrieved from local storage.");
var retrieved = localStorage.getItem("Recipe"); // Retrieve the item from storage
// test is the storage entry name
parsed = JSON.parse(retrieved); //var test is now re-loaded!
// we had to parse it from json
console.log(parsed)
}
// delete from array and update
function deletefromarray(id) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
console.log(notraw[id])
notraw.splice(id, 1);
localStorage.setItem("Recipe", JSON.stringify(notraw));
}
// This adds to local array, and then updates that array.
function addtoarray(ingredient, amount, unit) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.push([ingredient, amount, unit]);
localStorage.setItem("Recipe", JSON.stringify(notraw));
var recipeid = notraw.length - 1
console.log("recipe id:" + recipeid)
}
//The calculation function, that gets the ingredients from the array, and calculates what ingredients are needed
function calculate(multiplier) {
alert("Calculate function was called")
var length = recipearray.length - 1;
console.log("There are " + length + " ingredients.");
for (i = 0; i < length; i++) {
console.log("raw = " + recipearray[i + 1][1] + recipearray[i + 1][2]);
console.log("multiplied = " + recipearray[i + 1][1] / recipearray[0][2] * multiplier + recipearray[i + 1][2]);
}
}
// The save function, This asks the user to input the name and how many people the recipe serves. This information is later passed onto the array.
function save() {
var verified = true;
while (verified) {
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if (serves === "" || name === "" || isNaN(serves) === true || serves === "null") {
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
} else {
alert("sucess!");
var element = document.getElementById("header");
element.innerHTML = name;
var header2 = document.getElementById("details");
header2.innerHTML = "Serves " + serves + " people"
calculate(serves)
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.splice(0, 1, [name, serves, notraw.length])
localStorage.setItem("Recipe", JSON.stringify(notraw))
return;
}
}
}
// the recipe function processes the inputs for the different ingredients and amounts.
function recipe() {
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var count = "Nothing";
console.log("Processing");
if (isNaN(amount)) {
alert("You have to enter a number in the amount field")
} else if (ingredient === "" || amount === "" || unit === "Select Unit") {
alert("You must fill in all fields.")
} else if (isNaN(ingredient) === false) {
alert("You must enter an ingredient NAME.")
} else {
console.log("hey!")
// console.log(recipearray[1][2] + recipearray[1][1])
var totalamount = amount + unit
edit(ingredient, amount, unit, false)
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
}
}
function deleteRow(specified) {
// Get the row that the delete button was clicked in, and delete it.
var inside = specified.parentNode.parentNode.rowIndex;
document.getElementById('table').deleteRow(inside);
var rowid = inside + 1 // account for the first one being 0
console.log("An ingredient was deleted by the user: " + rowid);
// Remove this from the array.
deletefromarray(-rowid);
}
function insRow(first, second) {
//var first = document.getElementById('string1').value;
//var second = document.getElementById('string2').value;
// This console.log("insRow: " + first)
// Thisconsole.log("insRow: " + second)
var x = document.getElementById('table').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
var a = x.insertCell(2);
y.innerHTML = first;
z.innerHTML = second;
a.innerHTML = '<input type="button" onclick="deleteRow(this)" value="Delete">';
}
function populateheader() {
// Populate the top fields with the name and how many it serves
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
var element = document.getElementById("header");
element.innerHTML = notraw[0][0];
var header2 = document.getElementById("details");
// if statement ensures the header doesn't say '0' people, instead says no people
if (notraw[0][1] === 0) {
header2.innerHTML = "Serves no people"
} else {
header2.innerHTML = "Serves " + notraw[0][1] + " people"
}
console.log("Now populating Header, The Title was: " + notraw[0][0] + " And it served: " + notraw[0][1]);
}
function populatetable() {
console.log("Now populating the table")
// Here we're gonna populate the table with data that was in the loaded array.
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
if (notraw.length === 0 || notraw.length === 1) {
console.log("Array was empty.")
} else {
var count = 1;
while (count < notraw.length) {
amount = notraw[count][1] + " " + notraw[count][2]
insRow(notraw[count][0], amount)
console.log("Inserted Ingredient: " + notraw[count][0] + notraw[count][1])
count++;
}
}
}

Categories

Resources