Home > Software engineering >  How to compare previous value of variable with new variable value on each response node.js
How to compare previous value of variable with new variable value on each response node.js

Time:09-17

I'm running cron that is checking price each 30 seconds and will return me a value of asset. If the price will be different than previous price, i would like to log it.. I'm testing this because this will be very usable for me in the future ideas... price variable is holding the price. My goal is to do some action when the variable is different.

   //Stuff above the code like cron and general discord client.on ↑

   //this will log current price of asset
   console.log(price, 'PRICE UPDATED!')
    // tried to compare price however this is unsucessful, as it doesn't do anything...
    var Previousprice = null;
    function foo() {
      var Currentprice = $(price.toFixed(2))
      if (Previousprice == Currentprice) {
        $(price.toFixed(2))
        console.log('Price is same!')
      }
      Previousprice = Currentprice
      console.log('Price has changed!')
      //new discord action...
    }
   });
  });
 });
});

So far I also tried this, but i think this is completely useless and won't work that way...

    console.log(price, 'PRICE UPDATED!')
    let Previousprice = null;
    let Currentprice = price
    if (price) {
      let Previousprice = price.toFixed(2)
      console.log(price, 'Price defined')
    } else if(Previousprice === Currentprice) {
      console.log(price, 'Price is same') 
    } else if(Previousprice !== Currentprice) {
      let Previousprice = price.toFixed(2)
      console.log(price, 'Price changed!')  
    }
Logs: 
1.29739982471208 PRICE UPDATED!
1.29739982471208 Price defined
1.29739982471208 PRICE UPDATED!
1.29739982471208 Price defined
1.29660532105896 PRICE UPDATED!
1.29660532105896 Price defined

CodePudding user response:

You are re-declaring and assigning previousPrice = null; every 30 seconds. Can't give you specifics without seeing the surrounding code but what you generally want is a global variable like currentPrice, initialised to 0 when the app first runs. something like this should work:

// initialise a global variable with inital value of 0
let currentPrice = 0;

// Stuff above the code like cron and general discord client.on

console.log(price, 'PRICE UPDATED!');
if (price !== currentPrice) {
    console.log(`Price changed from ${currentPrice} to ${price}`);
    currentPrice = price;
}
else {
    console.log(`Price remains at ${currentPrice}`);
}

The first run will obviously change the price from 0 to the first initial price, but that's fine.

CodePudding user response:

Alright, so have you tried previous_price = current_price after having previous_price set to some price currently, run it, and then after console.log if it is different or something, then it gets set to current price, and then it will change after every internal?

This should work.

  • Related