How to pick a random function from a predefined set? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
If I have these functions defined:
function playZoomout() {
// do things
}
function playZoomin() {
// do things
}
function playPanright() {
// do things
}
function playPanleft() {
// do things
}
and am running this every four seconds:
var timer = setInterval(playZoomout,4000);
How can I replace "playZoomout" with a randomly selected function picked from the ones defined above? I'm looking for a jQuery or plain javascript solution.

Create an array of function references, then fetch an element randomly from the array and invoke it.
var fns = [playZoomout, playZoomin, playPanright, playPanleft]
setInterval(function () {
fns[Math.floor(Math.random() * fns.length)]();
}, 1000)
Demo: Fiddle

Add each functionname to an array, with numerical key indexing. Then, randomly generate a number between the lower and upper index and use a control structure to repeat the process.

Something like this should work (see http://jsfiddle.net/w6sdc/):
/* A few functions */
var a = function() {
alert("A");
}
var b = function() {
alert("B");
}
var c = function() {
alert("C");
}
/* Add the functions to an array */
var funcs = [a, b, c];
/* Select a random array index */
var i = Math.floor(Math.random() * 2) + 0;
/* Call the function at that index */
funcs[i]();
Wrapping the index selection and the function call in a setInterval should be straight forward from this point.

Related

How to check the array is of how many dimension in javascript? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
For example I have an array as follows & expected output is given.
In javascript how can we determine dynamically how many levels are there in my array ary.
var ary = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]];
Output: 3
var ary = ["a","b",["c","d"],"e",["f","g","i"]];
Output: 2
var ary = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
Output: 4
Here is a reccursive function that will traverse through the depths of the array and track the maximum of it. Note that the tracking is done via properties attach to the function itself.
var ary1 = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
function getDimension(arr, start) {
//Attach depth tracking properties to the function
if (start){
getDimension.depth = 0;
getDimension.maxDepth = 0;
}
//Track max depth
getDimension.depth++
if (getDimension.depth > getDimension.maxDepth)
getDimension.maxDepth++;
//Manage recursion
for (let element of arr)
if (element instanceof Array)
getDimension(element);
getDimension.depth--;
//In first level at this point
if (getDimension.depth === 0)
return getDimension.maxDepth;
}
let d = getDimension(ary1, true);
console.log(d);

cannot access the data of the first API in second API function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
<script>
/* 1st API*/
$.getJSON("http://cricapi.com/api/matches/?apikey=6aP8B4MImxSNxI6fevBmC2ZshO42",function(data){
var len = data.matches.length;
for(i=0;i<len;i++){
id = data.matches[i].unique_id;
ms = data.matches[i].matchStarted;
x = data.matches[i].date;
team_1 = data.matches[i]['team-1']
/* 2nd API*/
$.getJSON("https://cricapi.com/api/cricketScore/?apikey=6aP8B4MImxSNxI6fevBmC2ZshO42&unique_id="+id,function(data1){
console.log(team_1);
});
}
});
why i cannot get the team_1 of each match in second getJSON(). It is giving the output of same team name multiple times please help me to get the team names of each match. Appreciate any help!!
This "bug" is caused by hoisting.
Index i is stored as var, and it isn't in local for loop scope, so, when the index has gained its final value, the same value is used.
You can use let keyword:
for(let i=0;i<len;i++){ ..
so the variable will be loop scoped
Also Check out this link
function getScore(id, callback) {
$.getJSON("https://cricapi.com/api/cricketScore/?apikey=6aP8B4MImxSNxI6fevBmC2ZshO42&unique_id="+id, function(data1) {
callback(data1);
});
}
$( document ).ready(function() {
$.getJSON("http://cricapi.com/api/matches/?apikey=6aP8B4MImxSNxI6fevBmC2ZshO42",function(data){
var len = data.matches.length;
for(i=0;i<len;i++){
id = data.matches[i].unique_id;
ms = data.matches[i].matchStarted;
x = data.matches[i].date;
team_1 = data.matches[i]['team-1']
/* 2nd API*/
getScore(id, function(data1) {
console.log(data1);
});
}
});
});

Get line from file - NodeJS function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How to write a function that returns a line from file with nodeJS? The program runs in the loop, and each time you call the function should return a new string. And if the file ends begins again, with the first line.
This function takes randomly, how to do consistently?
var fs = require('fs');
// Get random line from file
function getRandSocks() {
var socks = fs.readFileSync('socks.txt').toString().split("\n");
var randsock = socks[Math.floor(Math.random()*socks.length)];
return randsock.split(':');
}
function loop() {
// ...
var socks = getRandSocks();
console.log('host: '+socks[0]+'port :'+socks[1]);
//...
loop();
}
Perhaps this would help. This gets the next line and wraps back to the start. It is based on the given getRandSocks function with minimal change.
var current_line = 0;
function getNextLines() {
var socks = fs.readFileSync('socks.txt').toString().split("\n");
var randsock = socks[current_line % socks.length];
current_line = (current_line + 1) % socks.length
return randsock.split(':');
}

Don't Repeat Yourself [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Would like to know if there is a better way to write this small block of code keeping DRY in mind. I see the similarities in the functions of course, but I am not sure how to shorten it. Also, I would like to know how much of a difference the shortening would make if any. Thank you, Jason
var adminAlert = {
alert: function() {
var sumAlert = sumSupport = sumCashout = sumPhone = 0;
$.getJSON("alertFeed.JSON", function(data) {
$.each(data.alertData, function(i, allAlerts) {
sumAlert += parseFloat(allAlerts.value);
sumSupport += parseFloat(allAlerts.support);
sumCashout += parseFloat(allAlerts.cashout);
sumPhone += parseFloat(allAlerts.phone);
$(".alertPoints").html(sumAlert);
$(".support-requests").html(sumSupport);
$(".cashout-giftcards").html(sumCashout);
$(".phone-verification").html(sumPhone);
});
});
}
};
The version undernearth is more DRY. Basically, to make your code DRY, you:
Identify repeated stuff. In your case it was parseFloat(allAlerts.foobar) and $(".blablabla").html(foobar);
Identify what is different between those repetitions. In your case you used a series of 4 keys within the allAlerts object: 'value', 'support', 'cashout' and 'phone'. Each of those 4 keys correspond to a CSS selector, e.g. cashout corresponds to ".cashout-giftcards";
Take what you identified in step 2 and put it into a declarative map. In your case:
{
'value': 'alertPoints',
'support': 'support-requests',
'cashout': 'cashout-giftcards',
'phone': 'phone-verification'
}
4. Replace what you identified in step 1 with a more unified / abstract code using the map you created in step 3. In your case, the four lines like sumCashout += parseFloat(allAlerts.cashout); can be replaced with only one line like sum[k] = parseFloat(allAlerts[k])
var
// To avoid repeatedly doing stuff like $(".alertPoints").html(sumAlert),
// we'll declare a concise map defining what will be updated by what:
map = {
'value': 'alertPoints', // later we will use this to update $(".alertPoints") with what comes from allAlerts.value
'support': 'support-requests', // later we will use this to update $(".support-requests") with what comes from allAlerts.support
'cashout': 'cashout-giftcards',
'phone': 'phone-verification'
},
adminAlert = {
alert: function(){
var
// Let's define an object that will hold the sums for us
sum = {},
// And also a variable to iterate our map;
k;
$.getJSON("alertFeed.JSON", function(data) {
$.each(data.alertData, function(i, allAlerts) {
// So we have 4 things to sum and update.
// They all are defined in our map.
// Lets go through the map and get things done:
for (k in map) {
// The value of k will be "value", "support" etc...
if (!(k in sum)) {
// In case the `sum` object does not yet have a key equal to the value of `k`, we initiate it.
// This is to have a start value of 0 to start adding to it:
sum[k] = 0;
}
// This is effectively the same as
// sumAlert += parseFloat(allAlerts.value) etc. etc.
// but written in unified manner to cover all the four cases.
// So when say `k` equals to `cashout`, this
// will be the same as `sum.cashout += parseFloat(allAlerts.cashout)`
sum[k] += parseFloat(allAlerts[k]);
// Again, a unified version of
// $(".alertPoints").html(sumAlert) etc. etc.
$('.' + map[k]).html(sum[k]);
}
});
});
}
};
In terms of difference — it is just easier to maintain / fix / debug / extend etc. Performance will probably be about the same.

Randomly selecting a function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am creating just a little test game type thing, and for part of it, I need a function to be randomly selected.
I have 2 altogether, and I just need to create maybe a 'random generator' somehow, which I can call, and it runs one of the 2 functions.
function function1() {
........code.........
}
function function2() {
........code.........
}
function generator() {
...random function selector...
}
Maybe something like that ^
Thanks in advance!
Yes, you can do that.
var myFuncArr = ["function1","function2"];
function generator(){
window[myFuncArr[Math.random() * (myFuncArr.length - 0) + 0]]();
}
JavaScript has an eval function that evaluates a string and executes it as code:
function generator(){
min = 1;
max = 5;
random = Math.floor(Math.random() * (max - min + 1)) + min;
param = "myParam";
eval("function"+random+"('"+param+"')");
}
Do you expecting like this
function method1(){
document.getElementById("sampleDiv").style.color = "red";
}
function method2(){
document.getElementById("sampleDiv").style.color = "yellow";
}
function method3(){
document.getElementById("sampleDiv").style.color = "orange";
}
function generator(id) {
eval("method"+id+"()")
}
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
setInterval(function(){generator(randomIntFromInterval(1,3))},3000);
Demo:
http://jsfiddle.net/hcmY9/3/

Categories