I'm trying to improve the following script by adding some randomness to it. Because right now it only bets on the "double_your_btc_bet_hi_button" id.
My idea is to generate a random number and make the bet based the its outcome. But I'm not sure how I supose to do that.
The id of the other bet buttom is "double_your_btc_bet_lo_button".
var minstake = 0.00000001; // valor base
var autorounds = 100; // n° de rolls
var handbrake = 0.0001; // valor lose pause game
var autoruns = 1;
function playnow() {
if (autoruns > autorounds ) { console.log('Limit reached'); return; }
document.getElementById('double_your_btc_bet_hi_button').click();
setTimeout(checkresults, 123);
return;}
function checkresults() {
if (document.getElementById('double_your_btc_bet_hi_button').disabled === true) {
setTimeout(checkresults, 246);
return;
}
var stake = document.getElementById('double_your_btc_stake').value * 1;
var won = document.getElementById('double_your_btc_bet_win').innerHTML;
if (won.match(/(\d+\.\d+)/) !== null) { won = won.match(/(\d+\.\d+)/)[0]; } else { won = false; }
var lost = document.getElementById('double_your_btc_bet_lose').innerHTML;
if (lost.match(/(\d+\.\d+)/) !== null) { lost = lost.match(/(\d+\.\d+)/)[0]; } else { lost = false; }
if (won && !lost) { stake = minstake; console.log('Bet #' + autoruns + '/' + autorounds + ': Won ' + won + ' Stake: ' + stake.toFixed(8)); }
if (lost && !won) { stake = lost * 2.1; console.log('Bet #' + autoruns + '/' + autorounds + ': Lost ' + lost + ' Stake: ' + stake.toFixed(8)); }
if (!won && !lost) { console.log('Something went wrong'); return; }
document.getElementById('double_your_btc_stake').value = stake.toFixed(8);
autoruns++;
if (stake >= handbrake) {
document.getElementById('handbrakealert').play();
console.log('Handbrake triggered! Execute playnow() to override');
return;
}
setTimeout(playnow, 111);
return;
}playnow()
I've tried to use Math.random but now it only bets lo and only plays once.
var minstake = 0.00000001; // valor base
var autorounds = 99999; // n° de rolls
var handbrake = 0.0001; // valor lose pause game
var autoruns = 1;
function getRandomNumber() {Math.floor(Math.random() * 2) + 1;
};
function playnow() {
if (autoruns > autorounds ) { console.log('Limit reached'); return; }
if (getRandomNumber!==1) {
document.getElementById('double_your_btc_bet_lo_button').click();
setTimeout(checkresultslo, 123);
return;
function checkresultslo() {
if (document.getElementById('double_your_btc_bet_lo_button').disabled === true) {
setTimeout(checkresultslo, 246);
return;}}}
if (getRandomNumber!==2) {
document.getElementById('double_your_btc_bet_hi_button').click();
setTimeout(checkresultshi, 123);
return;
function checkresultshi() {
if (document.getElementById('double_your_btc_bet_hi_button').disabled === true) {
setTimeout(checkresultshi, 246);
return;}}}
}
var stake = document.getElementById('double_your_btc_stake').value * 1;
var won = document.getElementById('double_your_btc_bet_win').innerHTML;
if (won.match(/(\d+\.\d+)/) !== null) { won = won.match(/(\d+\.\d+)/)[0]; } else { won = false; }
var lost = document.getElementById('double_your_btc_bet_lose').innerHTML;
if (lost.match(/(\d+\.\d+)/) !== null) { lost = lost.match(/(\d+\.\d+)/)[0]; } else { lost = false; }
if (won && !lost) { stake = minstake; console.log('Bet #' + autoruns + '/' + autorounds + ': Won ' + won + ' Stake: ' + stake.toFixed(8)); }
if (lost && !won) { stake = lost * 2.1; console.log('Bet #' + autoruns + '/' + autorounds + ': Lost ' + lost + ' Stake: ' + stake.toFixed(8)); }
if (!won && !lost) { console.log('Something went wrong');}
document.getElementById('double_your_btc_stake').value = stake.toFixed(8);
autoruns++;
if (stake >= handbrake) {
document.getElementById('handbrakealert').play();
console.log('Handbrake triggered! Execute playnow() to override');
}
setTimeout(playnow, 111);
playnow()
Related
I'm doing an API and the following code is used to retrieve users depending on filter. ( POST /users/search )
At the end of the function, I'm working with "LIMIT" and "OFFSET" in SQL because I want that nobody can retrieve more than 10 entries.
The code to generate the SQL query from WHERE is terrible. I am looking to improve it but I can't find a more effective way. Do you have any ideas?
function getSqlFilter(filter) {
var filterSql = '';
if (!util.isEmpty(filter)) {
var isFiltered = false;
if (filter.userId != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'pk_user in (' + filter.userId.toString() + ')';
isFiltered = true;
}
if (filter.username != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'username in (' + filter.username.toString() + ')';
isFiltered = true;
}
if (filter.email != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'email in (' + filter.email.toString() + ')';
isFiltered = true;
}
if (filter.society != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'society in (' + filter.society.toString() + ')';
isFiltered = true;
}
if (filter.firstname != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'firstname in (' + filter.firstname.toString() + ')';
isFiltered = true;
}
if ((filter.start != null) && (filter.end != null)) {
filter.start -= 1;
var limit = filter.end - filter.start;
if (limit <= 10) {
filterSql += 'LIMIT ' + limit + ' OFFSET ' + filter.start;
}
} else if (filter.start != null) {
filterSql += 'LIMIT 10 OFFSET ' + filter.start;
} else {
filterSql += 'LIMIT 10 OFFSET 0';
}
} else {
filterSql += 'LIMIT 10 OFFSET 0';
}
return filterSql;
}
Thanks for helping
You can simplify the redundant logic and utilize ES6 features for shorter syntax.
function getSqlFilter(filter = {}) {
const searches = Object.keys(filter);
const sLength = searches.length
let filterSql = sLength === 0 ? "LIMIT 10 OFFSET 0" : "WHERE ";
const map = {
userId: "pk_user",
username: "username",
email: "email",
society: "society"
}
const { start, end } = filter;
const hasOnlyStart = start !== undefined && end === undefined;
const hasStartAndEnd = start !== undefined && end !== undefined;
if (sLength) {
filterSql += searches.map(search => {
if(search === "start") {
return hasOnlyStart ? `LIMIT ${filter[search]} OFFSET 10` : "";
}
if(search === "end") {
return hasStartAndEnd ? `LIMIT ${filter[search]} OFFSET ${end - start}` : "";
}
return `${map[search]} in (${filter[search].toString()})`;
}).join(' AND ');
}
return filterSql;
}
I normally do this by starting with an always true condition
let filter= `...
WHERE 1 = 1`
Then you can simply append the filter
if (filter.username != null) {
filter += ' AND username in (' + filter.username.toString() + ')'
}
...
Hope this helps.
It is my anwser:
function getSqlFilter(filter) {
let sql = '';
let start = parseInt(filter.start);
let end = parseInt(filter.end);
delete filter.start;
delete filter.end;
const conditions = [];
const validKey = [...your key];
for (const key in filter){
if(validKey.indexOf(key) !== -1){
if(key === 'userId') conditions.push(`pk_user in (${filter[key].toString()})`);
else conditions.push(`${key} in (${filter[key].toString()})`);
}
}
if(conditions.length){
sql = ` WHERE ${conditions.join(' AND ')}`;
}
let limit = 10;
if (start) {
if(start < 0) start = 0;
if (end) {
let be_limit = start - end + 1;
if(be_limit <= 10 && be_limit >= 0) limit = be_limit;
}
} else {
start = 0;
}
sql += ` LIMIT ${limit} OFFSET ${start}`;
return sql;
}
If you don't want to change filter, please clone it before delete props.
i making a counter when everytime a users click a button it substracts 1 from the counter updates the node in firebase then return this change via another method with .valuechanges.subscribe
but everytime this happens it refreshes the whole page deleting all user inputs.
constructor(private dd: PlayerInfoProvider, private strge: Storage, private ss: Slot2machineProvider, private slotProvider: SlotProvider) {
this.slotProvider.getTries(this.dd.getCurrentUser()).valueChanges().subscribe(snapshot => this.gettries(snapshot));
}
gettries(snapshot) {
// this.playerObject = snapshot;
this.tries = snapshot;
}
runSlots() {
if (this.tries <= 0) {
alert("you cannot play anymore sorry!! but if you want you can purchase some more luck");
} else {
this.slotOne = Math.floor(Math.random() * 52) + 1;
this.slotTwo = Math.floor(Math.random() * 52) + 1;
this.slotThree = Math.floor(Math.random() * 52) + 1;
this.slotFour = Math.floor(Math.random() * 52) + 1;
this.slotFive = Math.floor(Math.random() * 52) + 1;
// this.sloty1 = '<p > "' + this.slotOne + '"</p>';
// this.sloty2 = '<p > "' + this.slotTwo + '"</p>';
// this.sloty3 = '<p > "' + this.slotThree + '"</p>';
// this.sloty4 = '<p > "' + this.slotFour + '"</p>';
// this.sloty5 = '<p > "' + this.slotFive + '"</p>';
if (this.slotOne !== this.slotTwo || this.slotTwo !== this.slotThree) {
this.loggerr = "<h2>sorry try again.. </h2>";
this.playerObject.tries = this.tries - 1;
//alert("you only have " + this.playerObject.tries + " chances left ");
// this.ss.substractTries(this.dd.getCurrentUser(), this.playerObject);
} else {
this.loggerr = "<p>jackpot!!!</p>";
}
}
}
So I've had a search around, and can't for the life of me understand why this would work perfectly in one browser, and not in the others. On line 13 I'm getting this error in Safari:
On Firefox, I don't get any errors, but the Script breaks in the same fashion. I've tried making the for loop for ( var p in productFamily ) or for ( let p of productFamily ) but it just breaks the script.
Am I looping incorrectly?
Here is my code:
$(window).load(function(){
// All possible families are defined here...
var productFamily = ["Beaches","Leios","Lull"];
// All possible product types are defined here...
var productType = ["Shelter","Restroom"];
// All possible product sizes are defined here...
var sizeRange = ["4x4","4x8","6x4","6x8","8x4","8x6"];
// Here we loop through each Family, Type and Size...
for ( let p in productFamily ) {
for ( let t in productType ) {
for ( let i in sizeRange ) {
// Get all of the select types...
$('select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' Size]"],'+
'select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Frame]"],'+
'select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Fasteners]"],'+
'select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Roof]"],'+
'select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Column Infill]"],'+
'select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Soffit and Sunscreen]"],'+
'select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Columns]"]').change(function(){
// Get the values of all the selects as they change...
var mySizeSelection = $('select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' Size]"]').val();
var myFrameSelection = $('select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Frame]"]').val();
var myFastenersSelection = $('select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Fasteners]"]').val();
var myColumnSelection = $('select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Columns]"]').val();
var myInfillSelection = $('select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Column Infill]"]').val();
var myRoofSelection = $('select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Roof]"]').val();
var mySoffitSelection = $('select[name="properties[' + productFamily[p] + ' ' + productType[t] + ' ' + sizeRange[i] + ' Soffit and Sunscreen]"]').val();
var empty;
// This changes the formatting of the size selection...
if ( mySizeSelection == "4x4" ) {
mySizeSelection = "44";
} else if ( mySizeSelection == "4x8" ) {
mySizeSelection = "48";
} else if ( mySizeSelection == "6x4" ) {
mySizeSelection = "64";
} else if ( mySizeSelection == "6x8" ) {
mySizeSelection = "68";
} else if ( mySizeSelection == "8x4" ) {
mySizeSelection = "84";
} else {
mySizeSelection = "86";
}
// This changes the formatting of the Frame selection...
if ( myFrameSelection == "Galvanised" ) {
myFrameSelection = "G";
} else if ( myFrameSelection = "Painted" ) {
myFrameSelection = "P";
} else {
myFrameSelection = "G";
}
// This changes the formatting of the Column selection...
if ( myColumnSelection == "Galvanised" ) {
myColumnSelection = "G";
} else if ( myColumnSelection = "Painted" ) {
myColumnSelection = "P";
} else {
myColumnSelection = "G";
}
// This changes the formatting of the Roof selection...
if ( productFamily[p] == "Beaches" ) {
if ( myRoofSelection == "Colorbond" ) {
myRoofSelection = "C";
} else if ( myRoofSelection == "Polycarbonite" ) {
myRoofSelection = "C";
} else if ( myRoofSelection == "None" ) {
myRoofSelection = "C";
} else {
myRoofSelection = "C";
}
} else {
if ( myRoofSelection == "Colorbond" ) {
myRoofSelection = "C";
} else if ( myRoofSelection == "Polycarbonite" ) {
myRoofSelection = "P";
} else if ( myRoofSelection == "None" ) {
myRoofSelection = "N";
} else if ( myRoofSelection == "Galvanised" ) {
myRoofSelection = "G";
} else if ( myRoofSelection == "Painted" ) {
myRoofSelection = "P";
} else {
myRoofSelection = "C";
}
}
// This changes the formatting of the Infill selection...
if ( myInfillSelection == "Yes" ) {
myInfillSelection = "I";
} else if ( (myInfillSelection == "No") || (myInfillSelection == "None" ) ) {
myInfillSelection = "N";
} else if ( myInfillSelection == "Solid Colour" ) {
myInfillSelection = "S";
} else if ( myInfillSelection == "Timber" ) {
myInfillSelection = "T";
} else {
myInfillSelection = "N";
}
// This changes the formatting of the Fastener selection...
if ( myFastenersSelection == "Galvanised" ) {
myFastenersSelection = "G";
} else if ( myFastenersSelection = "Stainless Steel") {
myFastenersSelection = "G";
} else {
myFastenersSelection = "G";
}
// This changes the formatting of the Soffit selection...
if ( mySoffitSelection == "Miniorb Soffit / No Sunscreen" ) {
mySoffitSelection = "CN";
} else if ( mySoffitSelection == "Timber Soffit / No Sunscreen" ) {
mySoffitSelection = "TN";
} else if ( mySoffitSelection == "Aluminium Soffit / No Sunscreen" ) {
mySoffitSelection = "AN";
} else if ( mySoffitSelection == "Miniorb Soffit / Miniorb Sunscreen" ) {
mySoffitSelection = "CC";
} else if ( mySoffitSelection == "Timber Soffit / Timber Sunscreen" ) {
mySoffitSelection = "TT";
} else if ( mySoffitSelection == "Aluminium Soffit / Aluminium Sunscreen" ) {
mySoffitSelection = "AA";
} else {
mySoffitSelection = "CN";
}
// If a Lull family item is selected, the src attribute url is updated... "C" is a hard-coded placeholder for Footing choices (between Cast-In or Slab Fixed), hence the "C" - Cast-In.
if ( productFamily[p] == "Lull" ) {
// If all choices have been chosen...
if ( mySizeSelection || myFrameSelection || myFastenersSelection ) {
var url = "//placeholder.com.au/"+ productFamily[p] + "_" + productType[t] + "/" + productFamily[p].toUpperCase() + "_" + mySizeSelection + myFrameSelection + "C" + myFastenersSelection + ".jpg";
$('.product-main-image img').attr("src",url);
console.log(url);
} else {
console.log("All options must be chosen.");
}
// If a Leios family item is selected, the src attribute url is updated... "C" is a hard-coded placeholder for Footing choices (between Cast-In or Slab Fixed), hence the "C" - Cast-In.
} else if ( productFamily[p] == "Leios" ) {
// If all choices have been chosen...
if ( mySizeSelection || myColumnSelection || myFrameSelection || myRoofSelection || myInfillSelection || myFastenersSelection ) {
var url = "//placeholder.com.au/"+ productFamily[p] + "_" + productType[t] + "_V3/" + productFamily[p].toUpperCase() + "_" + mySizeSelection + myColumnSelection + myFrameSelection + myRoofSelection + myInfillSelection + "C" + myFastenersSelection + ".jpg";
$('.product-main-image img').attr("src",url);
console.log(url);
} else {
console.log("All options must be chosen.");
}
// If a Beaches family item is selected, the src attribute url is updated... "C" is a hard-coded placeholder for Footing choices (between Cast-In or Slab Fixed), hence the "C" - Cast-In.
} else if ( productFamily[p] == "Beaches" ) {
// If all choices have been chosen...
if ( mySizeSelection || myFrameSelection || myRoofSelection || mySoffitSelection || myInfillSelection || myFastenersSelection ) {
var url = "//placeholder.com.au/"+ productFamily[p] + "_" + productType[t] + "/" + productFamily[p].toUpperCase() + "_" + mySizeSelection + myFrameSelection + myRoofSelection + mySoffitSelection + myInfillSelection + "C" + myFastenersSelection + ".jpg";
$('.product-main-image img').attr("src",url);
console.log(url);
} else {
console.log("All options must be chosen.");
}
} else {
console.log("No product family showing up...");
}
console.log("\n///////////////////////////////// END OF ON-CHANGE LOOP /////////////////////////////////\n\n");
}); // End of On change function.
} // End of sizeRange loop.
} // End of productType loop.
} // End of productFamily loop.
});
#Barmar hit the nail on the head - the type of for loop I was attempting was part of ES6 and not supported by all browsers, I ended up using the forEach function, courtesy of this link.
Here is a snippet of how I've used it in my script:
productFamily.forEach(function (value, p) {
productType.forEach(function (value, t) {
sizeRange.forEach(function (value, i) {
I'm constructing a quiz application and am having trouble verifying whether or not user answers are correct. The quiz contains 10 questions, and uses radio buttons to get answers from the user. For some questions, none of the answers register as correct, and for some of the other questions, all of the answers register as correct.
Each question has its own 'questionClass,' outlined like so:
function questionClass (q, a1, a2, a3, a4, n, c) {
this.question = q;
this.answer1 = a1;
this.answer2 = a2;
this.answer3 = a3;
this.answer4 = a4;
this.number = n;
this.correct = c;
Each of the question classes are created with the following formula:
var questionOne = new questionClass("quotation to be analyzed", 'answer1','answer2','answer3','answer4', number, 'correct');
questions.push(questionOne);
The function for verifying whether or not the user got the correct answer is here:
this.checkAnswer=checkAnswer;
function checkAnswer() {
if ($('input:radio[name=" ' + this.number + ' "]:checked').val() == this.correct) {
score++;
}
else if ($('input:radio[name=" ' + this.number + ' "]:checked').val() == this.correct) {
score++;
}
else if ($('input[id=" ' + this.answer3 + ' "]:checked') && (this.answer3 == this.correct)) {
score++;
}
else if ($('input[id=" ' + this.answer4 + ' "]:checked') && (this.answer4 == this.correct)) {
score++;
}
else {
console.log("you got the wrong answer");
}
}
The function for moving between questions is as follows:
$("#continue").click(function(){
counter++;
if (counter == 1) {
questions[x].display();
}
else if ((counter >= 1) && (counter <= 10)) {
if (questions[x].isSelected()) {
$('.warning').html("");
questions[x].checkAnswer();
$('.score').html("<p>Your score is " + score + " out of 10</p>");
x++;
if (x < 10){
questions[x].display();
}
}
}
else if ((counter >= 11) && (!questions[x].isSelected())) {
return;
}
else {
$('.warning').html("");
questions[x].checkAnswer();
$('.score').empty();
$('#container').html('<h1>You scored ' + score + ' out of 10.</h1></br>');
$('#container').append('<input type="button" id="tryAgain" value="Try Again!">');
}
});
The application can be viewed at this link:
http://dl.dropboxusercontent.com/u/91499081/QuizApp/quizApp.html
Fiddle http://jsfiddle.net/MCjna/
I can't figure this out I keep getting stuck in a loop. I don't know if I have my calculation or if statements in the right areas, please I could use some help. My output is like a end of day report. I could really use the help.
<script type="text/javascript">
<!--
// assignments
var cost, nachosCounter, moneyCollected, nachosRate, corndogRate, hotdogRate;
var hamAccum, hotdogAccum, corndogAccum, nachosAccum, hamburgerRate;
var beginDay, orderType, hamCounter, hotdogCounter, corndogCounter;
var totalHotdog, totalNachos, totalCorndog, totalHamburger, moneyCollected;
var hamburgerRate = 4;
var hotDogRate = 2;
var cornDogRate = 3;
var nachosRate = 5;
var hamCounter = 0;
var hotdogCounter = 0;
var corndogCounter = 0;
var nachosCounter = 0;
var beginDay = "yes"
//initalizing loop
beginDay = "yes"
//start loop
while (beginDay == "yes")
{
orderType = prompt("hamburger, hotdog, corndog, nachos", "");
if (orderType == "hamburger")
{
hamCounter = hamCounter + 1;
if (hamCounter == 1)
{
hamAccum = "<br>The total number of hamburgers purchased: " + hamCounter;
}
else
{
hamAccum = hamAccum + "<br>" + hamCounter;
}
}
else if (orderType == "hotdog")
{
hotdogCounter = hotdogCounter + 1;
if (hotdogCounter == 1)
{
hotdogAccum = "The total number of hotdog purchased:<br>" + hotdogCounter;
}
else
{
hotdogAccum = hotdogAccum + "<br>" + hotdogCounter;
}
}
if (orderType == "corndog")
{
corndogCounter = corndogCounter + 1;
if (corndogCounter == 1)
{
corndogAccum = "<br>The total number of corndogs purchased: <br>" + corndogCounter;
}
else
{
corndogAccum = corndogAccum + "<br>" + corndogCounter;
}
}
if (orderType == "nachos")
{
nachosCounter = nachosCounter + 1;
if (nachosCounter == 1)
{
nachosAccum = "<br>The total number of nachos purchased: <br>" + nachosCounter;
}
else
{
nachosAccum = nachosAccum + "<br>" + nachosCounter;
}
}
totalHotdog = hotdogCounter*hotDogRate;
totalHamburger = hamCounter*hamburgerRate;
totalCorndog = corndogCounter*cornDogRate;
totalNachos = nachosCounter*nachosRate;
moneyCollected = totalNachos+totalCorndog+totalHamburger+totalHotdog;
beginDay = prompt("More to add?", "yes");
}
//output
document.write(hotdogAccum);
document.write(hamAccum);
document.write(corndogAccum);
document.write(nachosAccum);
document.write("<br>The total dollar amount for hotdog: $ " + totalHotdog);
document.write("<br>The total dollar amount for hamburger: $ " + totalHamburger);
document.write("<br>The total dollar amount for corndogs: $" + totalCorndog);
document.write("<br>The total dollar amount for nachos: $" + totalNachos);
document.write("The total amount of money collected: $" + moneyCollected);
// -->
</script>