I'm trying to export the following function but when I do the rendering I don't see anything and it doesn't throw an error either. It must return a JSON object :
export const random = (resp) => { return resp}
((min,max) => {
let arr = [];
let coincidencia = {}
for(let i=0; i<10000; i++){ let valor_random = Math.floor(Math.random() * (max-min+1) + min)
arr.push(valor_random)
}
arr.forEach(function(numero){
coincidencia[numero] = (coincidencia[numero] || 0) + 1;
});
random(coincidencia)
}) (1,20) ;
Instead if I do like this, if it works. But that's not exactly what I want, I just want the code to be wrapped using IIFE :
export const random = (min,max) => {
let arr = [];
let coincidencia = {}
for(let i=0; i<10000; i++){ let valor_random = Math.floor(Math.random() * (max-min+1) + min)
arr.push(valor_random)
}
arr.forEach(function(numero){
coincidencia[numero] = (coincidencia[numero] || 0) + 1;
});
return coincidencia
}
Both are called as follows in my app.js file:
router.get('/random', (req,res) => {
res.json(random()); // para llamar al código que quiero que funcione.
});
Otherwise I have to do the same, but passing the parameters right there.
Thanks, I hope I was clear.
Check the examples on IIFE , in the second it says that:
And from what I understand, what you want is to return the result of the execution of your IIFE (which from what I could see is an object with 20 properties -from 1 to 20- with a numerical value that indicates the occurrence of each one of them within the 1000 randomly generated numbers) and not the function itself.
So starting from these two points we can do the following:
Which results in:
Basically assign the result of your IIFE to the
random
module property, and since it's an immediately executed function, you'll store the result and not the definition, then you can import that result into another module and see its value. Since it has already been auto-executed , there is no need to import and call the function, you can simply use it directly as if it were one more "variable" -despite being a constant- every time you re-execute the file you imported fromrandom
( importIife.js in this case), it will change its value and remain constant during that execution time.Extra:
If you make use of
Array.from()
and.reduce()
-and the arrow functions- you can reduce the code (really it only reduces two lines -without counting the comment lines- but it is more understandable, although if you wanted you could do the.reduce()
de directlyArray.from()
without going through the variablearray
) of your IIFE to the following: