new Date().getTime() showing NaN in JavaScript - javascript

I am trying to save the current time inside a temporary object inside the timestamp key using new Date.getTime() and push it into an array which is inside a globally accessible variable, GLOBAL_VAR.
But after I make the temporary variable and print its value it shows the timestamp is NaN I don't know why I can't get it inside the object (the console.log() and the result is shown below)
Also,
handleOrderMessage function is called when a socket.io event is received I don't know if that will affect the new Date.getTime() function, showing output:
console.log("TEMP OBJECT IS", tempObject)
/*
{
id: "-909e-11ea-9ede-066a42ffe1ae",
​price: "0.1",
​quantity: "0.1",
​side: "buy",
​timestamp: NaN
}
*/
function handleOrderMessage(msg) {
let d = new Date();
console.log(d.getTime());
if (msg['status'] === "PLACED") {
//for buy
if (msg['orderSide'] === "Buy") {
let tempObject = {
side: "buy",
id: msg["OrderID"],
timestamp: d.getTime(),
quantity: parseFloat(msg["Quantity"].toFixed(4)).toString(),
price: parseFloat(msg["Price"].toFixed(4)).toString()
}
//pushing to the global orders with price from msg as key
if (tempObject.price in GLOBAL_VAR.bidOrdersPricesAsKey) {
GLOBAL_VAR.bidOrdersPricesAsKey[tempObject.price].push(tempObject);
} else {
GLOBAL_VAR.bidOrdersPricesAsKey[tempObject.price] = [tempObject]
}
console.log("GLOBAL VAR BUY ORDERS PRICES ASK KEY", GLOBAL_VAR.bidOrdersPricesAsKey)
console.log("TEMP OBJECT IS", tempObject)
}
}

Following seems to be working fine, not sure why you're getting NaN. Please provide full working code to troubleshoot the issue.
doit();
function doit() {
let d = new Date();
let tempObject = {
side: "buy",
timestamp: d.getTime()
};
console.log(tempObject);
}

Related

Why is it when posting an object into a json file, one of the key/value always appears as curly braces?

So, i have this form button, when pressed, it posts and object into an array called "notes".
This object is filled with form field values, and a return of a function (ex.: a function that returns the creation date).
I've created another function to return the idm which is basicaly the lenght of the array "notes".
The creation date return, appears fine in the json file, however the id function always appears as curly braces.
I suspect it may be the async await keyworks, because if i create simple functio to return "hello", in the json file appears as "hello".
If someone knows this, i would appreciate the help.
The object being posted:
let userNote = { // the object
noteName: noteNameInput.value,
important: noteImportant.value,
reminder: noteDateInput.value,
noteMsg: noteMsgInput.value,
creationDate: creationDate(),
id: id()
}
let data = JSON.stringify(userNote);
The functions:
function creationDate(){
let today = new Date();
let day = today.getDate();
let month = today.getMonth()+1;
let year = today.getFullYear();
let currentDate = `${day}/${month}/${year}`;
return currentDate;
}
function id(){
return new Promise ((resolve, reject) => {
setTimeout(async () => {
const PORT = process.env.PORT || 3001;
const req = await fetch(`http://localhost:${PORT}/api`);
const data = await req.json();
let id_number = (data.notes.length);
const error = false;
//------------
if(!error){
resolve(id_number);
} else {
reject('Something went wrong!');
}
}, 1000);
});
}
The json file (*i started trying after "teste2"):
{"notes":[{"noteName":"teste1","important":"on","reminder":"2021-10-20","noteMsg":"teste1","creationDate":"7/10/2021"},{"noteName":"teste2","important":"on","reminder":"2021-10-28","noteMsg":"teste2","creationDate":"7/10/2021"},{"noteName":"teste3","important":"off","reminder":"2021-10-21","noteMsg":"teste3","creationDate":"7/10/2021","id":{}},{"noteName":"teste4","important":"off","reminder":"2021-10-19","noteMsg":"teste4","creationDate":"7/10/2021","id":{}},{"noteName":"teste5","important":"off","reminder":"2021-10-21","noteMsg":"teste5","creationDate":"7/10/2021","id":{}},{"noteName":"a","important":"off","reminder":"2021-10-21","noteMsg":"a","creationDate":"7/10/2021","id":{}}]}
*i've try with and without promises, to same end result. (the curly braces problem)

Why does my forEach() loop only execute once?

I seem to have encountered a problem while looping through an array. The loop seems to only execute once, no matter the size of the array. I tried using different methods of looping and the error still persists.
As background information, I'm trying to make a bot with which users can award each other points. Everything else seemed alright. The only issue is that I wish to set up a maximum amount of points one user can give to another in a day, and I'm having problems looping through the array which stores this information.
These are the relevant parts of my code:
var timer = []; //Timer stores the values.
const getTimerSenderIdTable = (id) => {
let found = false;
timer.forEach(function(dat) { // This is the problematic loop.
if (dat.id === id) {
found = dat;
}
})
console.log("loop end, results: " + found);
return found;
};
const timerManager = (senderId, targetId, pointSurp) => { //All arguments are integers.
let d = new Date()
if (getTimerSenderIdTable("date") !== d.getDate()) {
timer = [];
timer.push({"id":"date", "time":d.getDate()});
if (getTimerSenderIdTable("date")) {
if (getTimerSenderIdTable(senderId)) {
console.log("path 1");
} else {
console.log("path 2");
timer.push({"id":senderId, [targetId]:pointSurp});
}
}
} else {
if (getTimerSenderIdTable("date")) {
if (getTimerSenderIdTable(senderId)) {
console.log("path 3");
} else {
console.log("path 4");
timer.push({"id":senderId, [targetId]:pointSurp});
}
}
}
console.log(timer)
};
*Edit:
Thank you for your comments. Here is an example:
Calling timerManager(123456, 654321, 3) will produce the following output:
loop end, results: false
loop end, results: [object Object]
loop end, results: false
path 2
[ { id: 'date', time: 28 }, { '654321': 3, id: 123456 } ]
(This is a repost from comments. My appologies.)
It seems because of this line
if (getTimerSenderIdTable("date") !== d.getDate()) {
timer = [];
This will empty the array and next lines of code will only push single element
as #mbojko has pointed out, you'll want to use the find method for returning the found obj inside getTimerSenderIdTable function, like this
const getTimerSenderIdTable = (id) => {
return timer.find(item => item.id === id});
};

Why is this function breaking when it is placed inside of a promise?

I have a promise that retrieves entries from my Firebase Realtime Database, and using a callback, checks if the specific entries were made on today's date. The callback function (which works when not in the promise) results in the following error when I move it inside of the promise:
TypeError: Cannot read property 'checkIfEntryFromToday' of null
I have tried binding .this to the function in my constructor, but that does not help.
Here is the code:
Main function that calls the promise
getUsersHydration(){
return new Promise (resolve => {
const ref = this.props.firebase.db.ref(this.state.user)
ref.on("value", function(snapshot){
const userObject = (snapshot.val());
//pull ounces out of object and checks if the entry was made today
const dailyOunces = []
for (const key in userObject) {
let currentVal = userObject[key].ounces
let dateOfEntry = userObject[key].date
if (this.checkIfEntryFromToday(dateOfEntry)){
dailyOunces.push(currentVal)
}
}
//sums the total ounces
const sum = dailyOunces.reduce(function(a, b) { return a + b; }, 0)
resolve(sum)
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
})
}
function checkIfEntryFromToday that creates the error
checkIfEntryFromToday(milsToEvaluate){
const dayOfEntry = this.findDayByMils(milsToEvaluate)
const today = this.findDayByMils(new Date())
if (dayOfEntry === today) {
return true
} else {
return false
}
}
function called in checkIfEntryFromToday (maybe irrelevant, but since it's called I'll post it)
findDayByMils(givenDate){
//takes in the miliseconds and converts to string representing date
const date = new Date(givenDate)
const year = date.getFullYear().toString()
const day = date.getDay().toString()
const month = date.getMonth().toString()
const combinedDate = (day + year + month)
return combinedDate
}
Here is the problem: ref.on("value", function(snapshot){
You are using an anonymous function. Anonymous functions change this to be in the scope of the function (and you can't access the outside scope using this).
To get around the issue, change that line to: ref.on("value", snapshot => {

Why is previousHash not showing when I console.log my test blockchain?

I am trying learn more about blockchain by building a small project using JavaScript. Can anyone explain to me why the previousHash does not show when I console.log the test blockchain?
(npm install --save crypto-js if you need SHA256)
const SHA256 = require('crypto-js/sha256');
class Block{
//Index: (Optional) tells us where the block is in the chain
//Timestamp: tells us when the block was created
//Data: Can include any kind of data; for a currency you could store details of the transaction(transfer amount, sender id, receiver id)
//previousHash: String which contains the hash of the block which came before it (Ensures data integrity)
constructor(index, timestamp, data, previousHash = ''){
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
//Hash of this block
this.hash = this.calculateHash();
}
//Runs values from block through a hashing function to create a hash
calculateHash(){
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
//8.44
class Blockchain{
//Initializes blockchain
constructor(){
this.chain = [this.createGenesisBlock];
}
// first block needs to be created manually
//index, timeStamp, data, previousHash(there is none in this case)
createGenesisBlock(){
return new Block(0, "01/01/2017", "Genesis block", "0");
}
//Returns most recently added block
getLatestBlock(){
return this.chain[this.chain.length -1];
}
//adds a new block to the chain
addBlock(newBlock){
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash
//The chain is just an array so you can use regular array methods
this.chain.push(newBlock);
}
}
//create instance of blockchhain
let Coin = new Blockchain();
Coin.addBlock(new Block(1, "10/07/2017", {amount: 4}));
Coin.addBlock(new Block(2, "12/07/2017", {amount: 10}));
console.log(JSON.stringify(Coin, null, 4));
I expect the console.logged JSON file to contain the previousHash as well as the index, timestamp and data. It contains all except previousHash.
Thanks for the help have been scratching my head for a while trying to figure this out...
You forgot the paranthesis in the line with: this.chain = [this.createGenesisBlock()]; line, thus the first element of the chain will be a reference to a function, instead of an instance of a Block. Add the paranthesis, and it should work.
Additionally, you also forgot the paranthesis at another function call: when you are trying to call the function newBlock.hash = newBlock.calculateHash()
You also don't have hash in your console. This is the line with the error:
newBlock.hash = newBlock.calculateHash
calculateHash is a function
newBlock.hash = newBlock.calculateHash()
Now it is working:
{
"chain": [
null,
{
"index": 1,
"timestamp": "10/07/2017",
"data": {
"amount": 4
},
"hash": "8f84adcf036e9aa052a4d7e689c7b8b06070b851eff535870f5cb8f7d53ab05a"
},
{
"index": 2,
"timestamp": "12/07/2017",
"data": {
"amount": 10
},
"previousHash": "8f84adcf036e9aa052a4d7e689c7b8b06070b851eff535870f5cb8f7d53ab05a",
"hash": "a2479e7df8f2a61f97f3ae4830aff93c0d43041b4a7cbb8079c2309a915d8945"
}
]
}

Iterate over a Js array with two objects (firebase)

I'm using firebase to make a chat application. I stumbled upon a little problem.
When making requests to the firebase database, firebase will return a JSON or JS object back (I'm new to this so I don't really know).
This is the structure of my database:
The first ID under the message tree is the client's ID which I get when a cidst connects to the application. The id's just below are the client'ID with whom the logged client chatted with and the Id below that is firebase generated ID for each message.
With this code (see below) I'm listening on the database to see if any messages have been added for notification purposes.
var ref = database.ref('messages/81k44hlET5cq2AorxLDxD1DeXV52/');
ref.on('value', gotData, errData);
function gotData(data) {
var msgs = data.val();
var keys = Object.keys(msgs);
console.log(msgs);
messages = new Array();
timestamp = new Array();
type = new Array();
for(var keys in msgs) {
if (msgs.hasOwnProperty(keys)) {
console.log(keys + " -> " + msgs[keys]);
messages.push(msgs[keys]);
}
}
}
The output of the code:
I'm getting an array with two objects. Until here everything works fine.
My problem is that I can't figure out how I can get my message properties from here using JavaScript since the Message-IDs are unknown.
What I mean is that I can't access the properties doing msgs[keys].id.message for example since ID is unknown.
var ref = database.ref('messages/81k44hlET5cq2AorxLDxD1DeXV52/');
ref.on('value', gotData, errData);
function gotData(data)
{
var msgs = data.val();
var keys = Object.keys(msgs);
console.log(msgs);
messages = new Array();
timestamp = new Array();
type = new Array();
for(var keys in msgs)
{
if (msgs.hasOwnProperty(keys)) {
console.log(keys , " -> " , msgs[keys]);
messages.push(msgs[keys]);
var k = msgs[keys];
for(var keys in k){
console.log( k[keys]);
}
//
}
}
You could iterate over your JavaScript object with the .forEach method, use Object.entries for this.
In the following code snippet, I am logging all message objects
const messages = {
kjzn5ef6ke2zlfzn: {
h6qjopdbgs5d6mv7f: {
gd73g4d5d9dvtjzj15: {
message: "k",
seend: "true",
timestamp: "26/6/2018 20",
type: "send"
},
kdaz8bamd6kprmq78: {
message: "k",
seend: "true",
timestamp: "26/6/2018 20",
type: "send"
}
}
}
};
Object.entries(messages).forEach(([id1, a]) => {
Object.entries(a).forEach(([id11, b]) => {
Object.entries(b).forEach(([id111, message]) => {
console.log(id1, '=>', id11, '=>', id111, ':', message)
});
});
});

Categories