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 }
Related
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>
);
I am trying to make a 'generic' P5.js sketch that I can tweak based on a passed-in parameter, with the intent being to be able to generate multiple sketches on a single page to show how different inputs work side-by-side.
Following the guide I see syntax like this (and I've extended it to fill in multiple divs:
const s = ( sketch ) => {
let x = 100;
let y = 100;
sketch.setup = () => {
sketch.createCanvas(500, 500);
console.log(idx);
};
sketch.draw = () => {
sketch.background(100);
sketch.fill(255);
sketch.rect(x,y,50,50);
sketch.text
};
};
let myp5_1 = new p5(s, document.getElementById('p5-sketch1'));
let myp5_2 = new p5(s, document.getElementById('p5-sketch2'));
let myp5_3 = new p5(s, document.getElementById('p5-sketch3'));
I am not great with ES6, but I'm struggling with passing a set of parameters in to be able to tweak the P5.js code.
What I would like to do is to pass in, say, an ID variable into each instance of s and have the sketch execute differently, rather than making three separate const s calls and duplicating data.
Create a function that takes idx and returns the original function.
const s = (idx) => ( sketch ) => {
let x = 100;
let y = 100;
sketch.setup = () => {
sketch.createCanvas(500, 500);
console.log(idx);
};
sketch.draw = () => {
sketch.background(100);
sketch.fill(255);
sketch.rect(x,y,50,50);
sketch.text
};
};
let myp5_1 = new p5(s(0), document.getElementById('p5-sketch1'));
let myp5_2 = new p5(s(1), document.getElementById('p5-sketch2'));
let myp5_3 = new p5(s(2), document.getElementById('p5-sketch3'))
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
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.
I'm implementing the game Tic Tac Toe/Naughts and Crosses in a functional programming style and have stumbled across a hurdle with curried functions.
I have a reoccurring pattern of functions in the form func(width, height, index) which I then wish to curry, binding width and height and leaving curriedFunc(index).
However the problem arises when I have functions that expect one of these curried functions to be defined at compile-time.
They cannot be defined at compile time, because they need input from the user to then bind the values to the function.
Below is some example code of the pattern I've encountered.
// Board indexes:
// 0 | 1 | 2
// ---+---+---
// 3 | 4 | 5
// ---+---+---
// 6 | 7 | 8
const getRowNumGivenWidth = w => i => Math.floor(i/w);
// I want to be able to declare nextIndexInRowGivenWidth() here, outside of main()
// but getRowNum() needs to be defined beforehand
const main = () => {
// User input:
const width = 3;
// ...
const getRowNum = getRowNumGivenWidth(width);
const nextIndexInRowGivenWidth = width => currentIndex => {
const rowNum = getRowNum(currentIndex);
const nextIndex = currentIndex + 1;
if (getRowNum(nextIndex) != rowNum)
result = nextIndex - width;
else
result = nextIndex;
return result;
};
const nextIndexInRow = nextIndexInRowGivenWidth(width);
const board = [0, 1, 2, 3, 4, 5, 6, 7, 8];
board.map(x => console.log(x, " -> ", nextIndexInRow(x)));
// ...
}
main();
The only way I can think of solving this is to pass the curried function as an argument (to nextIndexInRowGivenWidth() in this example).
However I don't think this is ideal as if a function requires a few similarly curried functions at run-time, it quickly becomes unwieldy to define and curry said function.
The ideal solution would be if I could somehow make the binding of the values dynamic, suppose I could put the declaration getRowNum = getRowNumGivenWidth(width); before main(). This way I could call something like getRowNum(someInt) to initialise getRowNum() which I could then use in other functions that are already expecting it to be defined.
As this is a reoccurring pattern in my code, I was wondering if there is a design pattern to achieve this.
I think you are looking for
const getRowNumGivenWidth = w => i => Math.floor(i/w);
const nextIndexInRowGivenWidth = width => {
const getRowNum = getRowNumGivenWidth(width);
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return currentIndex => {
const nextIndex = currentIndex + 1;
if (getRowNum(nextIndex) != getRowNum(currentIndex))
return nextIndex - width;
else
return nextIndex;
};
};
const main = () => {
// User input:
const width = 3;
const nextIndexInRow = nextIndexInRowGivenWidth(width);
// ...
}
Alternatively, you could define that nextIndexInRowGiven… function not with the width as the first curried parameter, but with getRowNum itself as the parameter:
const getRowNumGivenWidth = w => i => Math.floor(i/w);
const nextIndexInRowGivenRowNumGetter = getRowNum => currentIndex => {
const nextIndex = currentIndex + 1;
if (getRowNum(nextIndex) != getRowNum(currentIndex))
return nextIndex - width;
else
return nextIndex;
};
const main = () => {
// User input:
const width = 3;
const nextIndexInRow = nextIndexInRowGivenRowNumGetter(getRowNumGivenWidth(width));
// ...
}