Math.random() generating same number when put in a function - javascript

Hi I'm working on a react project in which I have to generate random ids so I made this function
const idGenerator = () =>{
Math.floor(Math.random() * 1000000)
}
when I'm using it directly like this it works fine generates different ids
{
id:Math.floor(Math.random() * 1000000)
}
but when I make function and use it like this it generates the same id why is that?
const idGenerator = () =>{
Math.floor(Math.random() * 1000000)
}
// using it to make an object
{
id: idGenerator
}

Did you tried it also with an return statement?
const idGenerator = () =>{
return Math.floor(Math.random() * 1000000)
}
Or shorter
const idGenerator = () => Math.floor(Math.random() * 1000000);
const idGenerator = () => Math.floor(Math.random() * 1000000);
let obj1 = {
id1: idGenerator(),
id2: idGenerator()
}
console.log(obj1);
Also you need to execute the function with parenthesis () otherwise your propertie will hold the reference to the function

Related

Can do a transform whenever the useState is updated? Only vanilla react

I working on this streamer leaderboard project that only allows vanilla React. However, you need to move the streamer up or down in real-time whenever their points go up or down in rank. Since this is frontend test, I only used a Math.random() to change the streamer's points state. The animation would be like this link below(of course without clicking). I was thinking CSS animations, but not really sure how I can connect an animation to a useState update. Below, is a bit of my code as a reference.
Animation Example
const [streamerList, setStreamersList] = useState<StreamerType[]>([]);
useEffect(() => {
const getData = async () => {
const res = await fetch(
'https://webcdn.17app.co/campaign/pretest/data.json'
);
const data = await res.json();
const item = data;
setStreamersList(item);
//error catch handle
};
getData();
}, []);
//for now lets just add the fetching and later move it into a new folder
useEffect(() => {
const randomizer = () => {
let newArr = [...streamerList];
const eleSelect = Math.floor(Math.random() * (streamerList.length - 1));
const status = Math.floor(Math.random() * 2);
switch (status) {
case 0:
newArr[eleSelect].score =
newArr[eleSelect].score + Math.floor(Math.random() * 500);
newArr = newArr.sort((a, b) => b.score - a.score);
setStreamersList(newArr);
break;
case 1:
newArr[eleSelect].score =
newArr[eleSelect].score - Math.floor(Math.random() * 500);
newArr = newArr.sort((a, b) => b.score - a.score);
setStreamersList(newArr);
break;
default:
console.log('test');
}
};
//need a randomizer which element in the array
const interval = setInterval(() => {
randomizer();
//add all the other randomize && we do the set add /sub the points here
//TODO: there is a gap between adding, it seems like it should be none should nonexistent
}, 100);
return () => clearInterval(interval);
}, [streamerList.length, streamerList]);
return (
// TODO: unique key prop is have issues here for some reason
<LeaderBoard>
{streamerList.map((ele, index) => (
<Streamer
number={index}
userId={ele.userID}
displayName={ele.displayName}
picture={ele.picture}
score={ele.score}
/>
))}
</LeaderBoard>
);

How to export variable inside a function to another module

I would like to generate an array and store the value inside a variable and export that variable in a way that i can acess it anywhere i want in my application.
const generateNewArray = () => {
var numberOfArrayItems = 40;
var currentArray = Array.from({ length: numberOfArrayItems }, () => Math.floor(Math.random() * 200) + 1);
return currentArray;
}
export { generateNewArray }
But, until right now i could only export the function. And when i invoke "generateNewArray" i get the function body as answer, and when i invoke "generateNewArray()" i get another random array, different from the original.
How can i acess the "currentArray" variable from anywhere in my application?
Thanks!
You need to create a local variable, set its value, and then export the variable itself:
const generateNewArray = () => {
var numberOfArrayItems = 40;
var currentArray = Array.from({ length: numberOfArrayItems },
() => Math.floor(Math.random() * 200) + 1);
return currentArray;
}
const myRandomArray = generateNewArray();
export { myRandomArray }

Run a function a random number of times

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 **/

The function `this` doesn't work in module of nodejs

I create a module with following
module.exports = {
GetRandomNum:(Min,Max)=>{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
},
mathCalculationtion:()=>{
var firstPlace = this.GetRandomNum(1, 9);
return firstPlace;
}
}
I run this above code and get an error at the line var firstPlace = this.GetRandomNum(1, 9);
at Object. mathCalculationtion (/home/sfud/projectland/lib/comlib.js)
Please help me, thank you.
You are using arrow functions. The this variable does exist within regular objects, but arrow functions pull their this from whatever this is when they're declared (unless you bind them, which would be an odd thing to do).
Change your functions to functions and it should work fine.
module.exports = {
GetRandomNum(Min,Max) {
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
},
mathCalculationtion() {
var firstPlace = this.GetRandomNum(1, 9);
return firstPlace;
}
}
Note: To use it this way, you will need to import the module and call the function with the . syntax.
// This will work
const myModule = require('./my-module');
console.log(myModule.mathCalculationtion());
// This will not work
const { mathCalculationtion } = require('./my-module');
console.log(mathCalculationtion());
This is because this within the function is whatever the x in x.myFunc() is. If you just call myFunc() directly, it has no idea which object to apply it to. If you want to get around this, either define your functions in your module separately and reference them by name in the module, then export each function, or you can use .bind().
Change this.GetRandomNum(1, 9) to module.exports.GetRandomNum(1, 9) or
declare your functions outside of the module.exports block:
var getRandomNum = (Min,Max) => {
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
var mathCalculationtion = () => {
var firstPlace = getRandomNum(1, 9);
return firstPlace;
}
then:
module.exports = {
getRandomNum,
mathCalculationtion
}
Use module.exports instead of this:
module.exports = {
GetRandomNum(Min,Max) {
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
},
mathCalculationtion() {
var firstPlace = module.exports.GetRandomNum(1, 9);
return firstPlace;
}
}
It works for me just fine in NodeJs v12.16.1.

typescript - calling function at random intervals in ionic

I would like to repeatedly call the changeStyle() function at random intervals
here is my code so far:
this.platform.ready().then(() => {
this.myFunction()
});
myFunction() {
var min = 5,
max = 10;
var rand = Math.floor(Math.random() * (max - min + 1) + min); //Generate Random number between 5 - 10
this.changeStyle()
setTimeout(this.myFunction, rand * 1000);
}
changeStyle() {
console.log('changing style');
this.sensorImage = 'path/to/image1';
setTimeout(() => {
this.sensorImage = 'path/to/image2';
},
2000);
}
the relevant html code is
<img id='35' (click)="changeStyle()"
src="{{sensorImage}}">
ideally what this should do is call the changeStyle() function repeatedly and randomly without any input from me. however, I get a runtime error saying:
'TypeError: this.changeStyle is not a function. (In 'this.changeStyle('')', 'this.changeStyle' is undefined)'
Can you update your setTimeout(this.myFunction, rand * 1000); function to,
setTimeout(this.myFunction.bind(this), rand * 1000);
I believe the issue is related to this context.
You could do something like this,
changeStyle() {
...
...
const randomMilliSeconds = Math.floor( Math.random() * 10 ) * 1000;
setTimeout(() => {
this.changeStyle();
}, randomMilliSeconds)
}
You just need to call changeStyle once, manually or using click event and it will call itself at random intervals.

Categories

Resources