Recursive java script function - out of control - javascript

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);
}

Related

Unable to capture image after publish HikVision demo page into iis

I need to develop an IP camera viewer and image capture website.
For that I have downloaded the WebSdk from Hikvision and run it without publish this website into any server at that time I can view live preview and capture the images from live preview too.
But when I publish this website into the IIS it stops capturing images.
I am calling "clickDeviceCapturePic" method all the time.
I am stuck at issue where I am not able to capture image from Hikvision camera.
It is not giving error and there is less documentation about anything.
If you have experience developing it .
Please give me advice .
Below is an code that I have tried.
// Initialize the plugin
// Save the currently selected window globally
var g_iWndIndex = 0; //You don’t need to set this variable. In the interface with window parameters, you don’t need to pass values. The development kit will use the current selection window by default.
var szIP = [];
var szPort = [];
var szUsername = [];
var szPassword = [];
var DocumentPath = "";
var DocumentName = "";
$(function () {
// var urlParams = new URLSearchParams(window.location.search);
DocumentName = $.urlParam("DocumentName");
DocumentPath = $.urlParam("DocumentPath");
// ReadTheJson
$.getJSON("../IPCameraCfg.json", function (data) {
// console.log(data);
szIP = data.IPCameras;
szPort = data.Ports;
szUsername = data.UserNames;
szPassword = data.Passwords;
}).fail(function () {
console.log("An error has occurred.");
});
// Check if the plugin has been installed
// console.log("installed ? ", WebVideoCtrl.I_CheckPluginInstall());
if (-1 == WebVideoCtrl.I_CheckPluginInstall()) {
alert(
"You have not installed the plugin yet, download and install WebComponents.exe!"
);
return;
}
/// Initialize plug-in parameters and insert plug-ins
WebVideoCtrl.I_InitPlugin(1350, 800, {
iWndowType: 3,
cbSelWnd: function (xmlDoc) {
g_iWndIndex = $(xmlDoc).find("SelectWnd").eq(0).text();
var szInfo = "Currently selected window number:" + g_iWndIndex;
// showCBInfo(szInfo);
},
});
WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin");
// Check if the plugin is up to date
if (-1 == WebVideoCtrl.I_CheckPluginVersion()) {
alert("New plug-in version detected, please update WebComponents.exe!");
return;
}
/// Window event binding
$(window).bind({
resize: function () {
var $Restart = $("#restartDiv");
if ($Restart.length > 0) {
var oSize = getWindowSize();
$Restart.css({
width: oSize.width + "px",
height: oSize.height + "px",
});
}
},
});
// //initialization date and time
var szCurTime = dateFormat(new Date(), "yyyy-MM-dd");
$("#starttime").val(szCurTime + " 00:00:00");
$("#endtime").val(szCurTime + " 23:59:59");
//The login and preview methods are called here with setTimeout. If called directly, the window will not open because it takes time to load
clickSetLocalCfg();
setTimeout(function () {
clickLogin();
}, 3000);
setTimeout(function () {
clickStartRealPlay();
}, 4000);
});
function clickLogin() {
// var szPort = "80";
//var szUsername = "admin";
//var szPassword = "5E12345#";
console.log("Test", szIP[i], szPort[i], szUsername[i], szPassword[i]);
for (var i = 0; i < szIP.length; i++) {
var iRet = WebVideoCtrl.I_Login(
szIP[i],
1,
szPort[i],
szUsername[i],
szPassword[i],
{}
);
}
}
function clickStartRealPlay() {
for (var i = 0; i < szIP.length; i++) {
iWndIndex = i;
var iRet = WebVideoCtrl.I_StartRealPlay(szIP[i], {
iWndIndex: iWndIndex,
});
}
}
// device capturing
function clickDeviceCapturePic() {
//var szInfo = "";
for (var i = 0; i < szIP.length; i++) {
// console.log("loop", i);
var szDeviceIdentify = szIP[i]; // $("#ip").val();
// var bZeroChannel =
// $("#channels option")
// .eq($("#channels").get(0).selectedIndex)
// .attr("bZero") == "true"
// ? true
// : false;
var iChannelID = i; //parseInt($("#channels").val(), 10);
var iResolutionWidth = parseInt(200, 10);
var iResolutionHeight = parseInt(200, 10);
// if (null == szDeviceIdentify) {
// return;
// }
// if (bZeroChannel) {
// // zero channel do not support device capturing
// return;
// }
var szPicName = DocumentName + "_" + i;
//szDeviceIdentify + "_" + iChannelID + "_" + new Date().getTime();
var iRet = WebVideoCtrl.I_DeviceCapturePic(
szDeviceIdentify,
iChannelID,
szPicName,
{
bDateDir: false, //generate the date file or not
iResolutionWidth: iResolutionWidth,
iResolutionHeight: iResolutionHeight,
}
);
if (0 == iRet) {
console.log(szPicName, "device capturing succeed!");
} else {
console.log(szPicName, "device capturing failed!");
}
}
// showOPInfo(szDeviceIdentify + " " + szInfo);
}
// time format
function dateFormat(oDate, fmt) {
var o = {
"M+": oDate.getMonth() + 1, //month
"d+": oDate.getDate(), //day
"h+": oDate.getHours(), //hour
"m+": oDate.getMinutes(), //minute
"s+": oDate.getSeconds(), //second
"q+": Math.floor((oDate.getMonth() + 3) / 3), //quarter
S: oDate.getMilliseconds(), //millisecond
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(oDate.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
);
}
}
return fmt;
}
// set local parameters
function clickSetLocalCfg() {
var arrXml = [],
szInfo = "";
arrXml.push("<LocalConfigInfo>");
arrXml.push("<PackgeSize>" + $("#packSize").val() + "</PackgeSize>");
arrXml.push("<PlayWndType>" + $("#wndSize").val() + "</PlayWndType>");
arrXml.push(
"<BuffNumberType>" + $("#netsPreach").val() + "</BuffNumberType>"
);
arrXml.push("<RecordPath>" + $("#recordPath").val() + "</RecordPath>");
arrXml.push("<CapturePath>" + $("#previewPicPath").val() + "</CapturePath>");
arrXml.push(
"<PlaybackFilePath>" + $("#playbackFilePath").val() + "</PlaybackFilePath>"
);
arrXml.push(
"<PlaybackPicPath>" + $("#playbackPicPath").val() + "</PlaybackPicPath>"
);
arrXml.push("<DeviceCapturePath>" + "C:\\Temp" + "</DeviceCapturePath>");
arrXml.push("<DownloadPath>" + $("#downloadPath").val() + "</DownloadPath>");
arrXml.push("<IVSMode>" + $("#rulesInfo").val() + "</IVSMode>");
arrXml.push(
"<CaptureFileFormat>" +
$("#captureFileFormat").val() +
"</CaptureFileFormat>"
);
arrXml.push("<ProtocolType>" + $("#protocolType").val() + "</ProtocolType>");
arrXml.push("</LocalConfigInfo>");
let K = WebVideoCtrl.I_SetLocalCfg(arrXml.join(""));
console.log(K, "Config set");
}
function clickGetLocalCfg() {
console.dirxml(WebVideoCtrl.I_GetLocalCfg(), "Local Cfg");
}
function StopStreaming() {
//console.log("Stop Streaming",({}));
for (var i = 0; i < szIP.length; i++) {
iWndIndex = i;
var iRet = WebVideoCtrl.I_Stop({
iWndIndex: iWndIndex,
});
}
}
$.urlParam = function (name) {
var results = new RegExp("[?&]" + name + "=([^&#]*)").exec(
window.location.href
);
if (results == null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
};

await not efficient in asynchronous function

I am trying to parse pdf datas asynchronously, then populate a JS object with the content of the pdf file, and then return it in a Promise.
I am using the "pdfreader" module and its method parseFileItems()
async function parsePdfDatas(filePath){
var output = {};
var reader = new pdfreader.PdfReader();
await reader.parseFileItems(filePath, function(err, item) {
// item treatment populating output Object
});
return output;
}
parsePdfDatas("./****.pdf").then( function(output) {
console.log(output);
});
The await statement doesn't work, anybody get an idea ?
EDIT
After xMayank answer, i tried as follows, which doesn't work neither:
const fs = require('fs');
var pdfreader = require("pdfreader");
var row = {
id: "",
muban: "",
get mID() {
this.id.slice(6,8);
},
tambon: "",
get tID() {
this.id.slice(4,6);
},
amphoe: "",
get aID() {
this.id.slice(2,4);
},
changwat: "",
get cID() {
this.id.slice(0,2);
}
}
function parsePdfDatas(filePath){
return new Promise(function(resolve, reject){
var output = {};
var reader = new pdfreader.PdfReader();
reader.parseFileItems(filePath, function(err, item) {
if(item && item.text && item.text.match(/^-{1,3}[0-9]{1,4}-{1,3}$/) === null && item.y != 2.887){
if(item.x === 2.388){
// If the row object contains a muban entry, we push it at the end of output
if(row.id !== ""){
//console.log(row);
output[row.id] = {mName : row.muban, tName : row.tambon, aName : row.amphoe, cName : row.changwat};
}
// new line, row object reinitialization
row.id = row.muban = row.tambon = row.amphoe = row.changwat = "";
}
// correction for ่ ้
if(item.R[0].T === "%E0%B8%BD") item.text = "่";
if(item.R[0].T === "%E0%B8%BE") item.text = "้";
if(item.x >= 2.388 && item.x < 11.303)
row.id += item.text;
else if(item.x >= 11.303 && item.x < 17.969)
row.muban += item.text;
else if(item.x >= 17.969 && item.x < 23.782)
row.tambon += item.text;
else if(item.x >= 23.782 && item.x < 29.698)
row.amphoe += item.text;
else if(item.x >= 29.698)
row.changwat += item.text;
console.log(item.R[0].T + " -> " + item.text);
//console.log(item.text + " : x = " + item.x + " | y = " + item.y);
}
});
resolve(output);
});
}
parsePdfDatas("./files/mubans0.pdf").then((output) => {
console.log(output);
});
Works fine.
const { PdfReader } = require("pdfreader");
function readFile(file){
return new Promise(function(resolve, reject){
new PdfReader().parseFileItems(file, function(err, item) {
if (err) reject(err);
else if (!item) resolve();
else if (item.text) resolve(item.text);
});
})
}
readFile("./****.pdf")
.then(result =>{
console.log("Here", result)
})

Received data from socket and sort and display

I received data from socket and I need to live sort this data and display.
My code looke like this but only display unsort data.
$.each( data.players, function( key, value ) {
var p = value.value[0]/1000;
$('<tr>'+
'<td>'+
'<p class="price">$'+ p.toFixed(2)+'</p>'+
'</td>'+
'</tr>').appendTo('#target').hide().fadeIn(700);
});
Second problem:
When data was sorted and displayed and socket receive new player, it shoud be added on right place.
Data to sort (each object with id have price atrubute):
data to sort
Try the following
var data = {};
// simulate async data retrieval from socket
setInterval(function() {
// random data
data[parseInt(getRandom(1, 10000))] = {};
// update dome when new data is received
updateDom();
}, getRandom(1000, 5000));
// call this method each time new data is received
updateDom();
function updateDom() {
var keys = [];
// add object keys to an array to be able to sort them
for (k in data) {
if (data.hasOwnProperty(k)) {
keys.push(parseInt(k));
}
}
keys.sort(function(a, b) {
// sort values
return (a < b) ? -1 : ((a > b) ? 1 : 0);
}).forEach(function(e) {
if ($('#target [key=' + e + ']').length === 0) {
// if we haven't printed this yet
// generate dom
var domE =
'<tr key="' + e + '"><td>' +
'<p class="price">$' + e + '</p>' +
'</td></tr>';
// get value of previous key
var prevKey = keys.indexOf(e) - 1;
prevKey = prevKey < 0 ? 0 : prevKey;
// get previous element
var keyBefore = $('#target [key=' + keys[prevKey] + ']');
// if this does not have previous key exchange html
if (keyBefore.length === 0) {
$('#target').html(domE);
} else {
keyBefore
.after(domE)
.hide()
.fadeIn(700);
}
}
});
}
// utils - ignore for real implementation
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target">Data here!</div>

Node.js / Javascript - Wait until method is finished

I'm writing a steam trade bot but I have the problem that the for-loop doesn't wait until the method which is inside the for-loop is finished. So the code doesn't work as it should.
for (i = 0; i < offer.itemsToReceive.length; i++) {
console.log(offer.itemsToReceive[i].market_hash_name);
community.getMarketItem(appid.CSGO, offer.itemsToReceive[i].market_hash_name, function(err, items) {
if (err) {
Winston.error("Error getting Marketprice");
} else {
var cacheItemPrice = items.lowestPrice;
totalValue += items.lowestPrice;
Winston.info("Item " + offer.itemsToReceive[i].market_hash_name + " is " + items.lowestPrice + " Cents worth");
if (items.lowestPrice <= minValue) {
minValue = items.lowestPrice;
}
}
});
}
If the loop doesn't wait until the method is finished, the variable i isn't correct in the method and I get a wrong result.
Edit:
Now when I put the code from #Cleiton into my function from which I want to return two values, the function returns the value before the method has time to change the them.
function checkItemPricesCashIn(offer) {
Winston.info("Getting itemprices from trade #" + offer.id);
var totalValue = 0;
var minValue = 50;
var executionList = [];
function getMarketItem(item) {
var market_hash_name = item.market_hash_name;
return function() {
community.getMarketItem(appid.CSGO, market_hash_name, function(err, items) {
if (err) {
Winston.error("Error getting Marketprice");
} else {
var cacheItemPrice = items.lowestPrice;
totalValue += items.lowestPrice;
Winston.info("Item " + market_hash_name + " is " + items.lowestPrice + " Cents worth");
if (items.lowestPrice <= minValue) {
minValue = items.lowestPrice;
}
}
(executionList.shift() || function() {})();
});
}
}
offer.itemsToReceive.forEach(function(item) {
executionList.push(getMarketItem(item));
});
if (executionList.length) {
executionList.shift()();
}
console.log(totalValue);
console.log(minValue);
return {
totalValue: totalValue,
minValue: minValue
}
}
Below is a complete working code, I hope this helps :)
function checkItemPricesCashIn(offer, cb) {
Winston.info("Getting itemprices from trade #" + offer.id);
var totalValue = 0;
var minValue = 50;
var executionList = [];
function getMarketItem(item) {
var market_hash_name = item.market_hash_name;
return function() {
community.getMarketItem(appid.CSGO, market_hash_name, function(err, items) {
if (err) {
Winston.error("Error getting Marketprice");
} else {
var cacheItemPrice = items.lowestPrice;
totalValue += items.lowestPrice;
Winston.info("Item " + market_hash_name + " is " + items.lowestPrice + " Cents worth");
if (items.lowestPrice <= minValue) {
minValue = items.lowestPrice;
}
}
(executionList.shift() || cb)(minValue,totalValue);
});
}
}
offer.itemsToReceive.forEach(function(item) {
executionList.push(getMarketItem(item));
});
if (executionList.length) {
executionList.shift()();
}
}
How to use:
checkItemPricesCashIn(yourOffer/*your offer*/, function(min, max){
//it will be execute just after
console.log('min', min);
console.log('max', max);
});
You could use some library as async https://github.com/caolan/async. And with it any async cycle as eachSeries or just each.
async.each(array, function(item, callback){
// do something with a item
// call callback when finished
callback();
});

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