Please compare:
// Version 1
const oneHour = 60 * 60
function checkTime(timePast) {
if (timePast<7 * 24 * oneHour) {
// Do something
}
}
// Version 2
const oneHour = 60 * 60
const oneWeek = 7 * 24 * oneHour
function checkTime(timePast) {
if (timePast<oneWeek) {
// Do something
}
}
During millions of calls to checkTime(), is version 2 faster than version 1, or is Node.js smart enough to make the extra calculation in version 1 only once?
You can easily check it like this:
const oneHour = 60 * 60
const oneWeek = 7 * 24 * oneHour;
const randomData = generateArray();
function generateArray () {
let arr = [];
for(i = 0; i < 10000000; i++) {
arr.push(Math.floor(Math.random() * 10))
}
return arr;
}
function checkTime1(timePast) {
if (timePast<7 * 24 * oneHour) {
Math.random()
}
}
function checkTime2(timePast) {
if (timePast<oneWeek) {
Math.random()
}
}
console.time('checkTime1');
randomData.forEach(i => checkTime1(i))
console.timeEnd('checkTime1');
console.time('checkTime2');
randomData.forEach(i => checkTime2(i))
console.timeEnd('checkTime2');
After several checks change order of "checkTime2" and "checkTime1", to be sure the result is valid. Seems Node.js is smart enough to make the extra calculation.
According to this article: Node.js Under The Hood #10 - Compiler Optimizations! Node's compiler will perform Constant Folding optimization, such that const j = 3 + 9 will become const j = 12.
Related
In windows taskmanager you could find ethernet usage stats. My question is how do i get these with nodejs.
I've tried using both systemmonitor and os but values i get from them are TX/RX packets and i can't find a way to convert them to KB/s
I just ran into this issue myself and I wasn't able to find an answer, so I coded this myself. This works perfectly fine for me, it just puts the down- and upload rates from the specified network adapter, in my case Ethernet 2, in the networkSpeeds-object. Note, that this code uses PowerShell, so if you're not using windows or are unable to use PowerShell, this might not work
import * as child_process from "child_process";
let networkSpeeds = {
download: {
"bps": null,
"b/s": null,
"kbps": null,
"kb/s": null,
"mbps": null,
"mb/s": null,
"gbps": null,
"gb/s": null,
},
upload: {
"bps": null,
"b/s": null,
"kbps": null,
"kb/s": null,
"mbps": null,
"mb/s": null,
"gbps": null,
"gb/s": null,
},
lastUpdate: Date.now(),
lastBytesReceived: 0,
lastBytesSent: 0,
};
setInterval(() => {
child_process.exec(`powershell "Get-NetAdapterStatistics -Name 'Ethernet 2'"`, (error, stdout, stderr) => {
if (error) {
console.log(error);
} else {
let response = stdout.trim().replace(/( ){2,}/g, " ");
let bytesReceived = response.split("\n")[2].split(" ")[response.split("\n")[2].split(" ").length - 4];
let bytesSent = response.split("\n")[2].split(" ")[response.split("\n")[2].split(" ").length - 2];
let timePassed = Date.now() - networkSpeeds.lastUpdate;
// Compare the current BytesReceived and BytesSent to the last time the function was called
let bytesReceivedSinceLastUpdate = bytesReceived - networkSpeeds.lastBytesReceived;
let bytesSentSinceLastUpdate = bytesSent - networkSpeeds.lastBytesSent;
// Check, what the timeDifference is and calculate the speed
let downloadSpeed = bytesReceivedSinceLastUpdate / (timePassed / 1000);
let uploadSpeed = bytesSentSinceLastUpdate / (timePassed / 1000);
networkSpeeds.download["bps"] = downloadSpeed * 8;
networkSpeeds.download["b/s"] = downloadSpeed;
networkSpeeds.download["kbps"] = downloadSpeed * 8 / 1000;
networkSpeeds.download["kb/s"] = downloadSpeed / 1000;
networkSpeeds.download["mbps"] = downloadSpeed * 8 / 1000000;
networkSpeeds.download["mb/s"] = downloadSpeed / 1000000;
networkSpeeds.download["gbps"] = downloadSpeed * 8 / 1000000000;
networkSpeeds.download["gb/s"] = downloadSpeed / 1000000000;
networkSpeeds.upload["bps"] = uploadSpeed * 8;
networkSpeeds.upload["b/s"] = uploadSpeed;
networkSpeeds.upload["kbps"] = uploadSpeed * 8 / 1000;
networkSpeeds.upload["kb/s"] = uploadSpeed / 1000;
networkSpeeds.upload["mbps"] = uploadSpeed * 8 / 1000000;
networkSpeeds.upload["mb/s"] = uploadSpeed / 1000000;
networkSpeeds.upload["gbps"] = uploadSpeed * 8 / 1000000000;
networkSpeeds.upload["gb/s"] = uploadSpeed / 1000000000;
networkSpeeds.lastBytesReceived = bytesReceived;
networkSpeeds.lastBytesSent = bytesSent;
networkSpeeds.lastUpdate = Date.now();
}
});
fs.writeFileSync("temp.json", JSON.stringify(networkSpeeds, null, 6));
}, 1000);
I am trying to make a function that randomizes the placement of some clouds I imported, but the problem is, it generates the amount of clouds, but in the same position! I randomized the position, but when the code runs I have like 10 clouds in the same position. What can I do? this is the code:
loader.load('/clouds/clouds1/scene.gltf', function (clouds1) {
var clouds1array = []
function addClouds1(){
for (var i = 1; i < 10; i++) {
const clouds1Mesh = clouds1.scene
const clouds1Position = clouds1Mesh.position
clouds1Position.x = Math.random() * 10
clouds1Position.y = Math.random() * 10
clouds1Position.z = (Math.random() - 0.5 ) * 300
clouds1Mesh.scale.setX(0.05)
clouds1Mesh.scale.setY(0.05)
clouds1Mesh.scale.setZ(0.05)
scene.add(clouds1Mesh)
clouds1array.push(clouds1Mesh)
}
}
addClouds1()
})
edit: clouds1.scene structure is this:
I don't know why it has this amount of children, I tried to solve with the answer, but it still does not work. The 3rd child in the end contains the mesh, and I tried using that for it to work, but it says that I cannot use it in the scene.add() function
edit: I solved the problem! I just had to put the for loop outside the load function
for(let i = 0; i < 30; i+= 3)
loader.load('/clouds/clouds1/scene.gltf', function (clouds1) {
const cloud = clouds1.scene
const child1 = clouds1.scene.children[0].children[0].children[0].children[2].children[0]
child1.material = new THREE.MeshStandardMaterial({ emissive: 'white', emissiveIntensity: 0.5})
cloud.scale.set(0.05, 0.05, 0.05)
cloud.position.x = (Math.random() - 0.5) * 500
cloud.position.y = (Math.random() + ((Math.random() + 20 ) + 70))
cloud.position.z = (Math.random() - 1) * 500
cloud.rotation.x = Math.random()
cloud.rotation.y = Math.random()
cloud.rotation.z = Math.random()
scene.add(cloud)
})
The GLTFLoader results, which you have as clouds1 is a generic object, from which you properly extract clouds1.scene. However, clouds1.scene is also a single Scene object. If you have 10 clouds in the GLTF model you loaded, then clouds1.scene will have 10 children, and you will need to loop through them like this:
loader.load('/clouds/clouds1/scene.gltf', function (clouds1) {
var clouds1array = []
const clouds1Children = clouds1.scene.children
for (var i = 1; i < 10; i++) {
const clouds1Mesh = clouds1Children[i]
const clouds1Position = clouds1Mesh.position
clouds1Position.x = Math.random() * 10
clouds1Position.y = Math.random() * 10
clouds1Position.z = (Math.random() - 0.5 ) * 300
clouds1Mesh.scale.setX(0.05)
clouds1Mesh.scale.setY(0.05)
clouds1Mesh.scale.setZ(0.05)
scene.add(clouds1Mesh)
clouds1array.push(clouds1Mesh)
}
})
I am building an application that generates a view of space with a random number of clickable stars. So far I am generating the stars as so:
const makeStars = () => {
var num = Math.floor(Math.random() * 7 + 2);
return (
<div className="starWrapper">
<Star
name={makeid}
starType={starList[Math.floor(Math.random() * 6 + 1)]}
></Star>
<h2>Star: {makeid()}</h2>
</div>
);
};
This is working great, but I want this function to run a random number of times when the pages loads. Here is my attempt so far
const makeStars = () => {
var num = Math.floor(Math.random() * 7 + 2);
var count = 0
if (count < num) {
window.setTimeout(function() {
return(<div className="starWrapper"><Star name={makeid} starType={starList[Math.floor(Math.random() * 6 + 1)]}></Star><h2>Star: {makeid()}</h2></div>
{() => count + 1})
}, 10);
}
but so far this isn't returning anything and I'm not sure why. I don't know if setTimeout is the best tool for the job, and I'm open to any other suggestions you have.
The full page of code is viewable here.
This is the function that can be ran a random amount of times.
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function createstars(randnum) {
If (randnum > 0) {
/** Do logic here **/
createstars((randnum - 1))
}
}
createstars(rand(1,10)) /** set min and max to your liking , the rand function is inclusive **/
So this is my first attempt with React.
I have to calculate the (total)price for a reservation.
The reservation price is determined by a few factors:
Length of the boat: €1,25 for every meter
The amount of people: €1 per person
Use of electricity: €1,25 a day
Let's say the boat is 10m long and 2 people are on there who use electricity. They stay for 2 days. The calculation would be like the following:
BoatLength(10) * 1.25 * 2 = 25
AmountOfPeople(2) * 1 * 2 = 4
UseOfElectricity(true) = 1.25 * 2 = 2.5
total_price = €25 + €4 + €2.5 = €21.5
I try to implement that in my code, which looks like this:
import React, { Component } from 'react'
import BoatForm from "./BoatForm";
import StayForm from "./StayForm";
export default class PriceCalculator extends Component {
/**
* So, we created a form for the customers so that they can register their boat.
* Now we want to let them know how much their reservation costs.
* The size of the boat, amount of people, amount of days and use of electricity are all parameters.
*/
constructor(props) {
super(props)
this.state = {
boat_length: '',
amount_of_people: '',
arrival_date: '',
leave_date: '',
use_of_electricity: '',
box_number: ''
}
}
/**
* We use date fields in our form to define the stay date of the customer.
* That means we have to calculate the days ourselves.
*/
calculateStayTime() {
const ArrivalDate = new Date(this.state.arrival_date);
const LeaveDate = new Date(this.state.leave_date);
// calculate difference
const DiffTime = Math.abs(LeaveDate - ArrivalDate);
const DiffDays = Math.ceil(DiffTime / (1000 * 60 * 60 * 24));
let AmountOfDays = DiffDays;
return AmountOfDays;
}
/**
* Prices per day:
* - Price per meter: 1,25
* - Price per person: 1
* - Price for using electricity: 1,25
*/
calculatePrice() {
const BoatLength = this.state.boat_length;
const meter_price = 1.25;
const Persons = this.state.amount_of_people;
const persons_price = 1;
let price_per_day = BoatLength * meter_price + Persons * persons_price;
const electricity_price = 1.25;
const use_of_electricity = true;
// ? = if statement
price_per_day = price_per_day + (use_of_electricity ? electricity_price : 0);
// const total_price = price_per_day * AmountOfDays;
}
}
I struggle with passing the variables from calculateStayTime() to calculatePrice(). Can anyone help me with how to formulate my calculation to React.JS?
You need to use the result of calculateStayTime inside calculatePrice. You can assign the stay time value to a variable but I'd probably just replace the last line: // const total_price = price_per_day * AmountOfDays; can be replaced with const total_price = price_per_day * this.calculateStayTime(); which should give you what you need.
I have a formula that calculates the experience based on a certain level and another that calculates the level based on the given experience.
But the second function does not return the expected value.
const levels = 40;
const xp_for_first_level = 1000;
const xp_for_last_level = 1000000;
const getExperience = level => {
const B = Math.log(xp_for_last_level / xp_for_first_level) / (levels - 1);
const A = xp_for_first_level / (Math.exp(B) - 1.0);
const old_xp = Math.round(A * Math.exp(B * (level - 1)));
const new_xp = Math.round(A * Math.exp(B * level));
return new_xp - old_xp;
};
const getLevel = experience => {
const B = Math.log(xp_for_last_level / xp_for_first_level) / (levels - 1);
const A = xp_for_first_level / (Math.exp(B) - 1.0);
return Math.ceil(Math.log(experience / A) / B);
};
console.log(getLevel(xp_for_first_level)); // -9
console.log(getLevel(xp_for_last_level)); // 30
Expected result 1 and 40, but returns -9 and 30.
Can anyone help?
Anyone enlighten me, please?
I think the formula should change, i tried with this and it given correct return.
const getLevel = experience => {
const B = Math.log(xp_for_last_level / xp_for_first_level) / (levels + 1);
const A = xp_for_first_level - 1;
return Math.ceil(Math.log(experience / A) / B);
};