Why the Code After Array.foreach doesn't execute? - javascript

I am trying to get value of a global variable (screenDisplay) after completing the for each portion.
But it seems whenever the 2nd Part is put before the 1st Part, the value that i am supposed to get from screenDisplay comes undefined and the console throws an error.
*error
TypeError: Cannot read properties of undefined (reading 'toFixed')
Why does the screenDisplay's value gets affected when part 2 is kept after part 1?
To find the error directly input values to the screen without using calculator key. ex. (2+3)
Live Link Here
const screenDisplay = document.getElementById("screen-input-selector");
const result = () => {
focusInitiate();
try {
**//1st Part**
// * auto multiplication feature
displaylocalStorageDATA();
const screenItems = [...screenDisplay.value];
let screenPosition = screenDisplay.selectionStart;
screenItems.forEach((item, index) => {
let indexno = index + 1;
if (
screenItems.length != indexno &&
![")", "+", "-", "*", "/"].includes(screenItems[index + 1]) &&
item == ")"
) {
let remainingDataFirstPortion = screenItems.slice(0, index + 1); //selects and stores the rest of the portion of the text after cursor
let remainingDataLastPortion = screenItems.slice(
index + 1,
screenItems.length
);
const clearedArray = remainingDataFirstPortion.concat("*");
const clearedArray1 = clearedArray.concat(remainingDataLastPortion);
screenDisplay.value = clearedArray1.join("");
displaylocalStorageSTORE();
screenDisplay.setSelectionRange(screenPosition, screenPosition);
}
});
//2nd Part
const inputData = localStorage.getItem("display");
if (inputData != null) {
//when inputdata and screendisplay value are same
if (inputData == screenDisplay.value) {
//when local storage has some value
displaylocalStorageREMOVE();
// screenDisplay.value = eval(localStorage.getItem("display"));
screenDisplay.value = Function("return " + inputData)().toFixed(4); //using function constructor instead of EVAL function cause EVAL() executes the code it's passed with the privileges of the caller
displaylocalStorageSTORE();
} else {
//when inputdata and screendisplay value are not same
displaylocalStorageREMOVE();
screenDisplay.value = Function(
"return " + screenDisplay.value
)().toFixed(4);
displaylocalStorageSTORE();
}
} else {
//when local storage is empty
screenDisplay.value = Function("return " + screenDisplay.value)().toFixed(
4
);
displaylocalStorageSTORE();
}
} catch (error) {
console.log(error);
};

Problem Resolved.
displaylocalStorageDATA() (which reassigns locally saved data to the global variable) of Part 1 was causing the problem. It was redefining the screenDisplay.value.
Removing that line has solved the problem.
Thanks, Everyone.

Related

I have a usestate that I want to set I want to set to a value !==null within a function

I am trying to set a state var within a function so when a form button is pressed, the value of the usestate will not equal null anymore. Because the form will not equal null this will perform a different action in my code if this button has been pressed.
Only issue is it seems the variable setReg cannot be set inside of a function as it will not be a global variable. Is there a workaround here?
//the usestate
const [Reg, setReg] = useState(null)
//the function
const updateEthers = () => {
let tempProvider = new ethers.providers.Web3Provider(window.ethereum);
setProvider(tempProvider);
let tempSigner = tempProvider.getSigner();
setSigner(tempSigner);
//Here I am saying if setreg is null as set in the state then perform this
if (setReg == null) {
let tempContract = new ethers.Contract(
phonecontractAddress,
Register_abi,
tempSigner)
setContract(tempContract)
}
//Else use a different function
else {
let
tempContract = new ethers.Contract(
codecontractAddress,
Code_abi,
tempSigner)
setContract(tempContract)
}
}
//I have a button when pressed calls this
const setRegister = async (event) => {
event.preventDefault();
const Hash = await ipfsbcupload(event.target.setText.value);
console.log("sending " + event.target.setText.value + " to the contract");
contract.set(Hash);
setPhoneNum(event.target.setText.value)
let setReg = 1
//let setReg = 1 so that the setReg will no longer be null is the theory so the form will choose the other option when pressed now.
//...
}
setReg() is available globally; however you're missing the function brackets at the end (setReg vs setReg()). That said, what I believe you want to reference is reg.
/* Note that I've made `reg` lowercase to follow camelCase rules */
const [reg, setReg] = useState(null)
const updateEthers = () => {
// this will run fine and is likely the code you want
if (reg == null) { }
// this will return an error - setReg is a function and so needs the parentheses behind it as setReg() - otherwise it will say it's not defined
if (setReg == null) { }
// this doesn't make sense because setReg is just setting what reg should be, it's not a value itself
if (setReg() == null) { }
}

Google Scripts - getFrom() is not a function error

I had this working before, without an issue, however ever since I put a filter in to remove all threads with more than 1 email it is now coming up with the not a function error. I remove the filter and it still comes up with the error, unsure what has caused this to completely break on me
function extractEmails() {
var htmlBody = getEmailHtml();
var labelName = "auto-reply-incoming";
// get all email threads that match label
var receivedSearchQuery = "label:"+labelName+" -is:sent";
var threads = GmailApp.search(receivedSearchQuery, 0, 500);
threads.forEach ((t, i) => {
let messages = t.getMessages();
let name = messages.getFrom();
let messageCount = t.getMessageCount();
if (messageCount > 1) {
label.removeFromThread(t);
}
if (messageCount <= 1) {
message.reply("Hi " +name+" \n" + "insert text here");
}
});
};
accidentally removed part of the script, fixed with the following code:
messages.forEach ((m, j) => {
let name = m.getFrom();
m.reply("Hi " +name+" \n" + "insert text here");
});
Replace
let name = messages.getFrom();
by
let name = messages[0].getFrom();
The above because getFrom() is method from Class GmailMessage but messages is an Array.
Reference
https://developers.google.com/apps-script/reference/gmail/gmail-message#getfrom

boolean does not change in function JavaScript

I have the following code:
const ships = (length) => {
isSunk = false
console.log('BEFORE: ' + isSunk)
const shipSize = length
let hits = []
const hitLocation = location => {
hits.push(location);
isSunk = true;
console.log('INSIDE: ' + isSunk)
}
console.log('AFTER: ' + isSunk)
return {
isSunk,
hitLocation,
hits,
shipSize
}
}
const two = ships(2)
two.hitLocation(1)
two.hitLocation(2)
console.log('FINAL: ' + two.isSunk)
console.log('HITS: ' + two.hits)
Is there a reason why isSunk is not saved as true when I call it in the end?
Is it due to the nested functions?
When you set the boolean into the object, it is that value. It is not a reference to the variable. So when you change the variable, the value you saved inside of the object that you returned is not updated.
You can use a function to get the value
const ships = (length) => {
isSunk = false
console.log('BEFORE: ' + isSunk)
const shipSize = length
let hits = []
const hitLocation = location => {
hits.push(location);
isSunk = true;
console.log('INSIDE: ' + isSunk)
}
console.log('AFTER: ' + isSunk)
return {
isSunk: () => isSunk,
hitLocation,
hits,
shipSize
}
}
const two = ships(2)
two.hitLocation(1)
two.hitLocation(2)
console.log('FINAL: ' + two.isSunk())
Other option is to use a class.
class Ship {
hits = [];
constructor(length) {
this.shipSize = length;
}
get isSunk() {
return this.hits.length === this.shipSize;
}
hitLocation (location) {
this.hits.push(location);
console.log('INSIDE: ' + this.isSunk)
}
}
const two = new Ship(2)
two.hitLocation(1)
two.hitLocation(2)
console.log('FINAL: ' + two.isSunk)
The reason this happens is that isSunk is just a local variable and a value in contrast to hits which is also a local variable but an array and thus just a reference not a value.
As you return the object when calling ship() these values and the reference get returned in an object.
Now when you call hitLocation() it uses the local variable hits to add an entry to the array and as the array is just a reference the local variable hits and the hits in the two object have the same reference so they point to the same memory location, thus the update can be seen using the returned object.
On the other hand hitLocation() also modifies the local variable isSunk but as you do not return that and it is not a reference the object stored in variable two is not updated.
The best way to fix this to my mind is using a class instead of a object here. This will be much more concise and clear than returning and/or passing the object you want to perform some action on to a function all the time.

Variable unchanged and value is undefined inside Firebase callback function

I am working on a firebase project. During testing the
return user.val().name;
will return an
undefined
value however the
console.log(user.val().name)
will return the actual string stored in the .name field. Why is that. Also even if assign the
user.val().name
to a variable, the variable remains undefined.Please help figure out why this happens. I am printing it to a csv.
Here is my code:
var database = firebase.database();
var ref2 = database.ref('information/');
var id;
var name;
ref2.on("value", function (one) {
one.forEach(function (two) {
if (typeof two.val().Id !== 'undefined') {
id = two.val().Id;
name = program(id); //name undefined
}
else {
id = "";
}
csv = name + "," + id +"\n";
});
download(csv);
});
};
function program (id) {
var database = firebase.database();
var ref = database.ref("users/" + id + "/");
ref.on('value',function(user){
if (typeof user.val().name === 'undefined') {
return null;
}
else {
console.log(user.val().name); //this doesnt show undefined
return user.val().name; //this shows undefined when returned to the name variable
}
})
}
Note: In the firebase database, the name value is not null. It has a string added to it.

How do I get the gender from a particular user when updating a different table? Azure mobile services

I have a table called Subscription and another table called Client I need the gender of the Client who owns the subscription every time I make an update. Here's my update script:
function update(item, user, request) {
var subscriptionId = item.id;
var subscriptionActivitiesTable = tables.getTable("SubscriptionActivity");
var userTable = tables.getTable("User");
var activityTable = tables.getTable("Activity");
var userGender = userTable.where({id: item.UserId}).select('Gender').take(1).read();
console.log(userGender);
activityTable.where({PlanId:item.PlanId, Difficulty: item.Difficulty}).read({
success: function(results){
var startDate = item.StartDate;
results.forEach(function(activity)
{
var testDate = new Date(startDate.getFullYear(),startDate.getMonth(), startDate.getDate());
testDate.setDate(testDate.getDate() + activity.Sequence + (activity.Week*7));
subscriptionActivitiesTable.insert({SubscriptionId: subscriptionId,
ActivityId: activity.id, ShowDate: new Date(testDate.getFullYear(),
testDate.getMonth(), testDate.getDate()), CreationDate: new Date()});
})
}
});
var planWeeks = 12;//VER DE DONDE SACAMOS ESTE NUMERO
var idealWeight = 0;
if (userGender === "Male")
{
idealWeight = (21.7 * Math.pow(parseInt(item.Height)/100,2));
}
else
{
idealWeight = (23 * Math.pow(parseInt(item.Height)/100,2));
}
var metabolismoBasal = idealWeight * 0.95 * 24;
var ADE = 0.1 * metabolismoBasal;
var activityFactor;
if (item.Difficulty === "Easy")
{
activityFactor = 1.25;
}
else if(item.Difficulty === "Medium")
{
activityFactor = 1.5;
}
else
{
activityFactor = 1.75;
}
var caloricRequirement = ((metabolismoBasal + ADE)*activityFactor);
activityTable.where(function(item, caloricRequirement){
return this.PlanId === item.PlanId && this.Type != "Sport" &&
this.CaloricRequirementMin <= caloricRequirement &&
this.CaloricRequirementMax >= caloricRequirement;}, item, caloricRequirement).read({
success: function(results)
{
var startDate = item.StartDate;
results.forEach(function(activity)
{
for (var i=0;i<planWeeks;i++)
{
var testDate = new Date(startDate.getFullYear(),startDate.getMonth(), startDate.getDate());
testDate.setDate(testDate.getDate() + activity.Sequence + (i*7));
subscriptionActivitiesTable.insert({SubscriptionId: subscriptionId,
ActivityId: activity.id, ShowDate: new Date(testDate.getFullYear(),
testDate.getMonth(), testDate.getDate()), CreationDate: new Date()});
}
})
}
})
request.execute();
}
I tried the code above and clientGender is undefined. As you can see I want to use the gender to set the idealWeight.
The read() method expects a function to be passed in on the success parameter - it doesn't return the result of the query like you'd think.
Try something like this instead:
function update(item, user, request) {
var clientTable = tables.getTable("Client");
var clientGender = 'DEFAULT';
clientTable.where({id: item.ClientId}).select('Gender').take(1).read({
success: function(clients) {
if (clients.length == 0) {
console.error('Unable to find client for id ' + item.ClientId);
} else {
var client = client[0];
clientGender = client.Gender;
// since we're inside the success function, we can continue to
// use the clientGender as it will reflect the correct value
// as retrieved from the database
console.log('INSIDE: ' + clientGender);
}
}
});
// this is going to get called while the clientTable query above is
// still running and will most likely show a value of DEFAULT
console.log('OUTSIDE: ' + clientGender);
}
In this sample, the client table query is kicked off, with a callback function provided in the success parameter. When the query is finished, the callback function is called, and the resulting data is displayed to the log. Meanwhile - while the query is still running, that is - the next statement after the where/take/select/read fluent code is run, another console.log statment is executed to show the value of the clientGender field outside the read function. This code will run while the read statement is still waiting on the database. Your output should look something like this in the WAMS log:
* INSIDE: Male
* OUTSIDE: Default
Since the log shows the oldest entries at the bottom, you can see that the OUTSIDE log entry was written sometime before the INSIDE log.
If you're not used to async or functional programming, this might look weird, but as far as I've found, this is now node works. Functions nested in functions nested in functions can get kind of scary, but if you plan ahead, it probably won't be too bad :-)

Categories

Resources