Javascript isn't counting duplicates properly - javascript

I wrote a javascript to ask the user to input 5 numbers and check for the largest and smallest number. I can get it to display the largest and smallest number sometimes. The main problem is that I need to show an error message when the user inputs the smallest or largest number more than once. When i enter two large numbers in the first two boxes, I get an error message, but if I enter two small numbers, I don't get an error message. Here's my code, I suspect it's my else if, but I'm not totally sure.
EDIT: Sorry all, I forgot to mention that I'm restricted to only using if-else statements. No loops, no arrays. None of that. I know, I know, it's absolutely terrible.
function testProgram() {
var largestNum, smallestNum;
var num1, num2, num3, num4, num5;
var smallDupe, largeDupe;
var num1 = document.getElementById("Num1").value;
var num2 = document.getElementById("Num2").value;
var num3 = document.getElementById("Num3").value;
var num4 = document.getElementById("Num4").value;
var num5 = document.getElementById("Num5").value;
num1 = parseFloat(num1);
num2 = parseFloat(num2);
num3 = parseFloat(num3);
num4 = parseFloat(num4);
num5 = parseFloat(num5);
if ((!isNaN(num1)) && (!isNaN(num2)) && (!isNaN(num3)) && (!isNaN(num4)) && (!isNaN(num5))) {
largestNum = num1;
smallestNum = num1;
smallDupe = 0;
largeDupe = 0;
if(num2 >= largestNum) {
if(num2 == largestNum) {
largeDupe++;
}
else if (num2 <= smallestNum) {
if(num2 == smallestNum) {
smallDupe++;
}
smallestNum = num2;
smallDupe = 0;
} else {
largestNum = num2;
largeDupe = 0;
}
}
if(num3 >= largestNum) {
if(num3 == largestNum) {
largeDupe++;
}
else if (num3 <= smallestNum) {
if(num3 == smallestNum) {
smallDupe++;
}
smallestNum = num3;
smallDupe = 0;
} else {
largestNum = num3;
largeDupe = 0;
}
}
if(num4 >= largestNum) {
if(num4 == largestNum) {
largeDupe++;
}
else if (num4 <= smallestNum) {
if(num4 == smallestNum) {
smallDupe++;
}
smallestNum = num4;
smallDupe = 0;
} else {
largestNum = num4;
largeDupe = 0;
}
}
if(num5 >= largestNum) {
if(num5 == largestNum) {
largeDupe++;
}
else if (num5 <= smallestNum) {
if(num5 == smallestNum) {
smallDupe++;
}
smallestNum = num5;
smallDupe = 0;
} else {
largestNum = num5;
largeDupe = 0;
}
}
if (smallDupe > 0 || largeDupe > 0) {
// Display an error to the user stating that there are duplicates
window.alert("The smallest number and/or largest number contains is duplicated.");
console.log("Error notice");
}
// Reference out1 and out2 to the HTML document
var out1 = document.getElementById("Out1");
var out2 = document.getElementById("Out2");
out1.disabled = false;
out1.value = largestNum;
out2.disabled = false;
out2.value = smallestNum;
} else {
// Tells the user that their input is invalid and to input five numbers again
window.alert("Please input five numbers");
console.log("Error notice");
}
}

After you increment smallDupe, you're setting it back to 0. You need to handle the case of the current number being less than the smallest separately from it being equal. Also, if you enter the same number in the first sequence of boxes, it will be a duplicate of both the largest and smallest, and you need to allow this; the simplest way to do this is to use two separate groups of if/else if rather than combining them all into one big statement.
if(num2 > largestNum) {
largestNum = num2;
largeDupe = 0;
} else if (num2 == largestNum) {
largeDupe++;
}
if (num2 < smallestNum) {
smallestNum = num2;
smallDupe = 0;
} else if (num2 == smallestNum) {
smallDupe++;
}

Related

JavaScript function changes object argument and all associated variables

Links: https://github.com/VirxEC/CalcPlus/blob/master/assets/Library.js and https://virxec.github.io/CalcPlus/PreviewLibrary/ these are just links to the main code if needed. The first link is the source, the second is the run environment.
The function expo has a very critical issue. I will explain what it does, then I will explain the exact issue and what I've tried to fix it. So the function is meant to calculate exponents up to 264-1 digits long. (For the answer.) It works by running the multiplication function multiple times (on lines 196-197: final = multi(num1, num1); for (var i="2"; isLessThan(i, num2); i=add({num:i.split(""),isNeg:false,decimals:0}, {num:["1"],isNeg:false,decimals:0})) final = multi(final, num1);)
The objects that you see are passed into the isLessThan() function are examples of me passing pre-parsed numbers to the function doesn't have to re-parse them and take up computer resources. This passing of a pre-parsed object is where the error is. On line 197, you can see final = multi(final, num1); The final variable is not pre-parsed for obvious reasons, but num1 is. However, if you go into the chrome debugger and watch the num1 variable, the multi() function changes the content of the property num1.num from (if you did 264) from ["2"] to ["0","2"] causing and incorrect answer.
I've tested force-removing this behavior is intended for the multi function, but it shouldn't be modifying the argument. I've tried naming the variable something else, using const, and trying to set the object to be read-only nothing has worked. I've even tried something like this:
num1save = num1;
final = multi(num1, num1);
for (var i="2"; isLessThan(i, num2); i=add({num:i.split(""),isNeg:false,decimals:0}, {num:["1"],isNeg:false,decimals:0})) {
final = multi(final, num1);
num1 = num1save;
}
However, somehow, the variable manages to change num1save. Any variable referenced at some point to the object is changed. I have no idea why this is happening. This same thing happens with the isLessThan() function and the variable num2 on line 197.
This includes only the required code, so the lines won't match up:
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// https://github.com/VirxEC/CalcPlus/blob/master/LICENSE
function parseNums(num1pre, num2pre, mode) {
if (["string", "object"].indexOf(typeof num1pre) == -1) throw new TypeError("The first number wasn't a string (or object). It has to be a string (or object). Note that an object input is ment to submit a pre-parsed number.");
if (["string", "object"].indexOf(typeof num2pre) == -1) throw new TypeError("The second number wasn't a string (or object). It has to be a string (or object). Note that an object input is ment to submit a pre-parsed number.");
if (typeof mode != "number" || [1, 2, 3, 4, 5].indexOf(mode) == -1) throw new TypeError("The mode must be a number from 1-5.");
var num1 = num1pre,
num2 = num2pre,
skip = false,
stringMode1 = true,
stringMode2 = true,
neg = [false, false, false],
decimal = 0,
decimal1 = 0,
decimal2 = 0,
num1pos, num2pos, maxChar, numl;
if (num1.num != undefined) neg[1] = num1pre.isNeg, decimal1 = num1pre.decimals, num1 = num1pre.num, stringMode1 = false;
if (num2.num != undefined) neg[2] = num2pre.isNeg, decimal2 = num2pre.decimals, num2 = num2pre.num, stringMode2 = false;
if (stringMode1 && num1.split("-").length == 2) num1 = num1.split("-")[1], neg[1] = true;
if (stringMode2 && num2.split("-").length == 2) num2 = num2.split("-")[1], neg[2] = true;
if (neg[1] != neg[2] && mode != 1 && mode != 2) neg[0] = true;
if (stringMode1) num1 = num1.split('').filter(w => w != ",");
if (stringMode2) num2 = num2.split('').filter(w => w != ",");
num1pos = num1.indexOf("."), decimal1 = num1pos != -1 ? num1.filter(w => w != ".").length - num1pos : 0, num2pos = num2.indexOf("."), decimal2 = num2pos != -1 ? num2.filter(w => w != ".").length - num2pos : 0, decimal = mode == 1 || mode == 2 ? Math.max(decimal1, decimal2) : mode == 3 ? decimal1 + decimal2 : decimal1 - decimal2, maxChar = Math.max(num1.length, num2.length);
for (var i = 0; !skip && num2.length == maxChar && i < num2.length && (((neg[1] || neg[2]) && mode == 1) || mode == 2); i++)
if (+num2[i] > +num1[i]) neg[0] = true, skip = true;
if (decimal < 0) decimal = 0;
if (maxChar == num2.length && mode == 3) num1 = [num2, num2 = num1][0]
if (decimal1 != decimal2 && [1, 2].indexOf(mode) > -1) {
if (decimal1 == decimal)
for (var i = 0; i < decimal1 - decimal2; i++) num2.push("0");
else if (decimal2 == decimal)
for (var i = 0; i < decimal2 - decimal1; i++) num1.push("0");
}
if (num1.length != num2.length && [1, 2].indexOf(mode) > -1) {
numl = [num1.length, num2.length];
if (maxChar == numl[0])
for (var i = 0; i < numl[0] - numl[1]; i++) num2.unshift("0");
else if (maxChar != num1[0])
for (var i = 0; i < numl[1] - numl[0]; i++) num1.unshift("0");
}
if (mode == 3 && neg.every(e => (e == true))) neg[0] = false;
return {
num1: {
num: num1,
isNeg: neg[1],
decimals: decimal1
},
num2: {
num: num2,
isNeg: neg[2],
decimals: decimal2
},
isNeg: neg[0],
maxChar: maxChar,
decimals: decimal
};
}
function formatNums(final, decimals, neg) {
if (typeof final == "string") {
if (decimals > 0) {
final = final.split("");
final.splice(final.length - decimals, 0, ".");
final = final.join("");
}
} else if (typeof final == "object") {
if (decimals > 0) {
final = final.reverse();
final.splice(final.length - decimals, 0, ".");
final = final.join("");
} else final = final.reverse().join("");
}
final = neg[0] ? "-" + final : final;
final = ["", ".", "-"].indexOf(final) > -1 ? "0" : final;
return final;
}
function add() {
function tempadd(num1, num2) {
var parsedNums = parseNums(num1, num2, 1),
neg = [parsedNums.isNeg, parsedNums.num1.isNeg, parsedNums.num2.isNeg],
maxChar = parsedNums.maxChar,
decimal = [parsedNums.decimals, parsedNums.num1.decimals, parsedNums.num2.decimals],
num1 = parsedNums.num1.num,
num2 = parsedNums.num2.num,
time, final = [],
carry = "0",
finali;
if (neg[2]) return sub(parsedNums.num1, {
num: num2,
isNeg: false,
decimals: decimal[1]
});
else if (neg[1]) return sub(parsedNums.num2, {
num: num1,
isNeg: false,
decimals: decimal[2]
});
for (var i = maxChar - 1; i >= 0; i--) {
finali = maxChar - i - 1;
if (time != i + 1) carry = "0";
final[finali] = String(+num1[i] + (+num2[i]) + (+carry));
if (+final[finali] > 9) {
var temp = final[finali].split('');
final[finali] = temp[1], carry = temp[0], time = i;
if (i - 1 < 0) final.push(carry);
}
}
return formatNums(final, decimal[0], neg);
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = tempadd(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = tempadd(permfinal, a[i]);
return permfinal;
}
function sub() {
function tempsub(num1pre, num2pre) {
var parsedNums = parseNums(num1pre, num2pre, 2),
neg = [parsedNums.isNeg, parsedNums.num1.isNeg, parsedNums.num2.isNeg],
maxChar = parsedNums.maxChar,
decimal = [parsedNums.decimals, parsedNums.num1.decimals, parsedNums.num2.decimals],
num1 = parsedNums.num1.num,
num2 = parsedNums.num2.num,
final = [],
finali, fans;
if (neg[0] && !neg[1] && !neg[2]) num1 = [num2, num2 = num1][0];
else if (neg[1] && neg[2]) num1 = [num2, num2 = num1][0];
else if (neg[2] && !neg[1]) return add(parsedNums.num1, {
num: num2,
isNeg: false,
decimals: decimal[2]
});
else if (neg[1] && !neg[2]) return "-" + add({
num: num1,
isNeg: false,
decimals: decimal[1]
}, parsedNums.num2);
for (var i = maxChar - 1; i >= 0; i--) {
finali = maxChar - i - 1, fans = num1[i] - num2[i];
if (fans < 0 && i != 0) {
var j = i - 1;
final[finali] = String(fans + 10), num1[j] = String(num1[j] - 1);
while (num1[j] < 0 && j != 0) num1[j] = String((+num1[j]) + 10), j = j - 1, num1[j] = String(num1[j] - 1);
} else if (fans < 0 && i == 0) final[finali] = String(fans).split("-")[1];
else final[finali] = fans;
}
return formatNums(final, decimal[0], neg);
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = tempsub(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = tempsub(permfinal, a[i]);
return permfinal;
}
function isLessThan() {
function templessthan(num1, num2) {
var num = sub(num2, num1);
if (num.split("-").length == 1 && num != 0) return true;
return false;
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = templessthan(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = templessthan(permfinal, a[i]);
return permfinal;
}
function multi() {
function tempmulti(num1pre, num2pre) {
var parsedNums = parseNums(num1pre, num2pre, 3),
neg = [parsedNums.isNeg, parsedNums.num1.isNeg, parsedNums.num2.isNeg],
final = "",
decimals = parsedNums.decimals,
numArray = [],
num2 = parsedNums.num2,
num1 = parsedNums.num1;
if (num2.num.length == 1 && num2.num[0] == "1") return formatNums(num2.num, decimals, neg);
else if (num2.length == 1 && num2[0] == "0") return "1";
else {
final = add(num1, num1);
for (var i = "2"; isLessThan(i, num2); i = add({
num: i.split(""),
isNeg: false,
decimals: 0
}, {
num: ["1"],
isNeg: false,
decimals: 0
})) final = add(final, num1);
}
return formatNums(final, decimals, neg);
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = tempmulti(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = tempmulti(permfinal, a[i]);
return permfinal;
}
function expo() {
function tempexpo(num1pre, num2pre) {
var parsedNums = parseNums(num1pre, num2pre, 5),
num1 = parsedNums.num1,
num2 = parsedNums.num2,
decimals = parsedNums.decimals,
decimal2 = parsedNums.num2.decimals,
neg = [parsedNums.isNeg, parsedNums.num1.isNeg, parsedNums.num2.isNeg],
numArray = [],
final = "";
if (neg[1]) num1.num.unshift("-");
if (neg[2]) num2.num.unshift("-");
if (decimal2 > 0) {
// root_of_decimal2*10(num1)**(num2*(10*decimal2))
alert("Decimal exponents aren't supported yet");
throw new TypeError("Decimal exponents aren't supported yet");
} else {
if (num2.num.length == 1 && num2.num[0] == "1") return formatNums(num2.num, decimals, false);
else if (num2.num.length == 1 && num2.num[0] == "0") return "1";
else {
final = multi(num1, num1);
for (var i = "2"; isLessThan(i, num2); i = add({
num: i.split(""),
isNeg: false,
decimals: 0
}, {
num: ["1"],
isNeg: false,
decimals: 0
})) {
final = multi(final, num1);
console.log(num1, num2, i);
}
return final;
}
//Need to fix div -> if (neg[2]) return div("1", final);
}
}
var permfinal, a = arguments;
if (Array.isArray(a[0])) a = a[0];
permfinal = tempexpo(a[0], a[1]);
for (var i = 2; i < a.length; i++) permfinal = tempexpo(permfinal, a[i]);
return permfinal;
}
console.log(expo("2", "64"));
Why is this happening? Is there a work-around?
If you saw the previous post, sorry. I've been very frustrated with this bug.
Doing the following:
var num1save = JSON.parse(JSON.stringify(num1));
var num2save = JSON.parse(JSON.stringify(num2));
sets a save variable that isn't just a reference but is instead a good copy and then doing this to set the save:
num1 = JSON.parse(JSON.stringify(num1save));
num2 = JSON.parse(JSON.stringify(num2save));
doesn't prevent the problem from happening, but prevents it from causing any issues. Appling this in a way other than in the for loop would prevent the issue from happening.

What is the short form of this compare variable code

Is there a way that I can combine these two codes into one? I want to check if some variables are equal to 0 or equal to 1 or equal to 2 or greater than 2 and less than 5 or greater than 5. Should I write a code for each variable or I can write a code for all variables?
<script>
if (NRIRDL==0){
XRIRDL=0;
}
else if (NRIRDL == 1){
XRIRDL = 1;
}
else if (NRIRDL == 2){
XRIRDL = 1.8;
}
else if (NRIRDL > 2 && NRIRDL < 5){
XRIRDL = 0.9 * NRIRDL;
}
else {
XRIRDL = NRIRDL - 1;
}
// code below is the same as code above, but variables are different.
if (NRIRDR==0){
XRIRDR=0;
}
else if (NRIRDR == 1){
XRIRDR = 1;
}
else if (NRIRDR == 2){
XRIRDR = 1.8;
}
else if (NRIRDR > 2 && NRIRDR < 5){
XRIRDR = 0.9 * NRIRDR;
}
else {
XRIRDR = NRIRDR - 1;
}
</script>
actually, it can be written shorter with ternary operator and without multiple if conditions, check it out:
function getValue(n) {
return n >= 2 && n < 5 ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
}
var var1 = 0;
var var2 = 1;
var var3 = 2;
var var4 = 3;
var var5 = 5;
console.log(getValue(var1)); // outputs 0
console.log(getValue(var2)); // outputs 1
console.log(getValue(var3)); // outputs 1.8
console.log(getValue(var4)); // outputs 2.7
console.log(getValue(var5)); // outputs 4
Just use getValue(n) function: pass your variable and it will return needed value that can be stored into another variable like var XRIRDL = getValue(NRIRDL); or var XRIRDR = getValue(NRIRDR);
You could make it into a function:
function yourFunction(val) {
if (val == 0){
return 0;
}
else if (val == 1){
return 1;
}
else if (val == 2){
return 1.8;
}
else if (val > 2 && val < 5){
return 0.9 * val;
}
else {
return val - 1;
}
XRIDR = yourFunction(NRIDR);
XRIDL = yourFunction(NRIDL);
When you OR the two inputs together, you lose valuable information about which one of the two inputs triggered that condition.
Mike's answer might not fit your needs because you can't update the values independently of one another (i.e. if NRIDR == 0 and NRIDL == 2, it sounds like you don't want both XRIDR and XRIDL to equal 1.8.)
You could put it inside a function. Here's a copy paste of your code inside a function.
function xrirdr(dr_or_dl){
var XRIRDL = null;
if (dr_or_dl==0){
XRIRDL=0;
}
else if (dr_or_dl == 1){
XRIRDL = 1;
}
else if (dr_or_dl == 2){
XRIRDL = 1.8;
}
else if (dr_or_dl > 2 && dr_or_dl < 5){
XRIRDL = 0.9 * dr_or_dl;
}
else {
XRIRDL = dr_or_dl - 1;
}
return XRIRDL;
}
You can pass NRIRDL or NRIRDR in the function and it will get you your XRIRDL
<script>
if (NRIRDL==0 || NRIRDR==0 ){
XRIRDL=0;
XRIRDR=0;
}
else if (NRIRDL == 1 || NRIRDR == 1)){
XRIRDL = 1;
XRIRDR = 1;
}
else if (NRIRDL == 2 || NRIRDR == 2)){
XRIRDL = 1.8;
XRIRDR = 1.8;
}
else if ((NRIRDL > 2 && NRIRDL < 5) || (NRIRDR > 2 && NRIRDR < 5) ){
XRIRDL = 0.9 * NRIRDL;
XRIRDR = 0.9 * NRIRDR;
}
else {
XRIRDL = NRIRDL - 1;
XRIRDR = NRIRDR - 1;
}
</script>

Update a loop so that if 13 is a number between num1 and num2

I need to update a loop so that if 13 is a number between num1 and num2 (inclusive), then the loop skips it and continues to push the rest of the numbers to the array.
I am getting the error that I need to push 13 to the array. My updated code:
var addToArray = function(num1, num2) {
var array = [];
for (var i = num1; i <= num2; i++) {
if(num1 > 12 && num2 < 14 ){
continue;
}
array.push(i);
}
return array;
};
for(var i = 0; i < sum.length; i++){
if(sum[i] !== 13){
sumOfArray += sum[i];
}
I'm assuming num1 = 0 and num2 = sum.length. You should check to see if the item at sum[i] doesn't equal 13 and add the item if it doesn't. it will skip over the number 13 if you do.
var numsToAddExceptThriteen = function(num1, num2) {
var numsInArray = [];
var totalSum = 0;
//make sure we start with the smaller number;
if (num1 > num2) {
var tempNum = num2;
num2 = num1;
num1 = tempNum;
}
//cycle through values and skip 13
for ( var i = num1; i <= num2; i++ ) {
if ( i !== 13 ) {
numsInArray.push(i);
totalSum += i
}
}
//log both values
console.log(numsInArray);
console.log(totalSum);
};
numsToAddExceptThriteen(10, 80);
#Lkoprivica, I think what you will need is twofold. First you will need to define num1 and num2. I'm not sure how you are generating these numbers though, so cannot guess. As far as the loop, you could do something like so:
var num1, num2; //these should be populated with numbers from somewhere
for(var i = 0; i < sum.length; i++){
if( (sum[i] === 13 && sum[i] > num1 && sum[i] < num2 ) || (sum[i] === 13 && sum[i] < num1 && sum[i] > num2 ) ){
//we skip the else and move along if sum[i] is between num1 and num2 and if it equals 13
} else {
sumOfArray += sum[i];
}
}

calculating a textbox value

I am working on a requirement where I want to do some calculation on the numbers entered in the dxtextbox,
For example if I am entering:
123456789
then the calculation will be like
num1=1 *3;num2=2 *7;num3=3 ;num4=4 *3;num5=5 *7;num6=6;num7=7 *3;num8=8*7;num9=9;
sum=num1+num2+num3+num4+num5+num6+num7+num8+num9
if(sum != 0 && sum % 10 == 0){it will return true}else it should return false
I searched this in your documentation section but didn't got any thing.
Can you please help me to solve this requirement .
I have attached a sample solution where you can see the kind of validation structure I trying to accomplish this task.
Thank You
$(document).ready(function()
{
var enteredNumber = 123456789;
var numTotal = 0;
var multiplikator = Array(3,7,1);
var multiplikatorCnt = 0;
for(a=0;a < enteredNumber.toString().length; a++)
{
numTotal += parseInt((enteredNumber.toString())[a]) * multiplikator[multiplikatorCnt];
multiplikatorCnt++;
if(multiplikatorCnt > 2)
{
multiplikatorCnt = 0;
}
}
if(numTotal != 0 && numTotal % 10 == 0)
{
return true
}
else
{
return false
}
});
Edit: forgot to return true or false.
Shorter would be:
$(document).ready(function()
{
var enteredNumber = 123456789;
var numTotal = 0;
var multiplikator = Array(3,7,1);
for(a=0;a < enteredNumber.toString().length; a++)
{
numTotal += parseInt((enteredNumber.toString())[a]) * multiplikator[a % multiplikator.length];
}
if(numTotal != 0 && numTotal % 10 == 0)
{
return true
}
else
{
return false
}
});
Thank You for your quick response,I am able to solve it by my self
here is the code what I am using
var valuenum = $("#txt_value").dxTextBox("instance");
var checknumber = valuenum .option('value');
var arr = checknumber.split('');
var num1, num2, num3, num4;
num1 = (arr[0]) * 3;
num2 = (arr[1]) * 7;
num3 = (arr[2]);
num4 = (arr[3]) * 3;
var totalval = parseInt(num1) + parseInt(num2) + parseInt(num3) + parseInt(num4) ;
if (totalval != 0 && totalval % 10 == 0) {
return true;
}

How to make if/ else statement evaluate for all variables

I'm trying to create a game in which a user "bets" on if the next card will be in between the previous two shown. In order to calculate that, I created a random number through 52 and set it equal to an array variable value. I need a number 2-14 as opposed to 1-52 (to evaluate the # of the card in case 2 cards with same # and different suite show). To do that, I used slice to get the 1st letter of the array item and store it in a variable (num1, num2, numUser).
I then used if else statements to give the face cards (10, jack, queen, king, ace) # values. The issues is, I need to apply this to all 3 variables. Currently, the statement stops when it identifies a face card and sets the # value. If there are multiple face cards, the statement only applies to the first.
I tried wrapping this in a for loop and making it run 3 times- ex.(for (var i = 0; i > 3; i++), but that didn't work. Sorry if this is confusing, any help is greatly appreciated.
function outputCards(){
rand1 = Math.floor((Math.random() * 52));
rand2 = Math.floor((Math.random() * 52));
$('#cardUser').attr("src", "#");
if(rand1 == rand2){
rand2 = Math.floor((Math.random() * 52));
} else {
card1 = cards[rand1];
card2 = cards[rand2];
$('#cardOne').attr("src", "imgs/" + card1);
$('#cardTwo').attr("src", "imgs/" + card2);
}
}
function userCard(){
rand_user = Math.floor((Math.random() * 52));
if(rand_user == rand1 || rand_user == rand2){
rand_user = Math.floor((Math.random() * 52));
} else {
user_card = cards[rand_user];
$('#cardUser').attr("src", "imgs/" + user_card);
}
}
function outcome(){
userCard();
num1 = card1.slice(0,1);
num2 = card2.slice(0,1);
numUser = user_card.slice(0,1);
if(num1 == "j"){
num1 = 11;
} else if (num2 == "j") {
num2 = 11;
} else if (numUser === "j") {
numUser = 11;
} else if (num1 == "q") {
num1 = 12;
} else if (num2 == "q") {
num2 = 12;
} else if (numUser === "q") {
numUser = 12;
} else if (num1 == "k") {
num1 = 13;
} else if (num2 == "k") {
num2 = 13;
} else if (numUser === "k") {
numUser = 13;
} else if (num1 == "a") {
num1 = 14;
} else if (num2 == "a") {
num2 = 14;
} else if (numUser === "a") {
numUser = 14;
} else if(num1 == 1){
num1 = 10;
} else if(num2 == 1){
num2 = 10;
} else if(numUser == 1){
numUser = 10;
} else {
}
}
well theres more efficient ways to accomplish this, the most straightforward (and beginner friendly) one is to use 3 else if trees not a single one.
if(num1 == "j"){
num1 = 11;
} else if (num2 == "j") {
num2 = 11;
} else if (numUser === "j") {
numUser = 11;
...
you have these grouped together when they need to be separate
if(num1 == "j"){
num1 = 11;
} else if (num1 == "q") {
num1 = 12;
} else if (num1 === "k") {
num1 = 13;
...
if(num2 == "j"){
num2 = 11;
} else if (num2 == "q") {
num1 = 12;
} else if (num2 === "k") {
num2 = 13;
...
this can be accomplished by putting the if statements in a function
function outcome(number){
if(number == "j"){
return 11;
} else if (number == "q") {
return 12;
} else if (number === "k") {
...
} //etc
}
num1 = outcome(card1.slice(0,1))
num2 = outcome(card2.slice(0,1))
numUser = outcome(user_card.slice(0,1));
you can also create an object map to map the card letter with a number value
var cardMap = {
j: 11,
q: 12,
k: 13,
...
}
then you can do
num1 = cardMap[card1.slice(0,1)]
num2 = cardMap[card2.slice(0,1)]
numUser = cardMap[user_card.slice(0,1)]
An if-elseif block will stop execution whenever it finds a true conditional, regardless of how many you have.
So you want to evaluate the variable based on the first character, and you know that will always be the same, right? This is a great opportunity to use a simple function that does just that one job (as all functions should do).
function getCardValueFromFirstCharacter(character) {
// you may need to check for the number as well:
// if (character == "1") {
// return 1;
// } else if (character == "2") {
// return 2;
// }
// etc..
if (character == "j") {
return 11;
} else if (character == "q") {
return 12;
}
// etc..
}
Now, in your other function, your outcome function, you can call this one with each of your desired inputs:
function outcome() {
userCard();
num1 = getCardValueFromFirstCharacter(card1.slice(0,1));
num2 = getCardValueFromFirstCharacter(card2.slice(0,1));
numUser = getCardValueFromFirstCharacter(user_card.slice(0,1));
}
In this way, we have our single function that is solely responsible for identifying the value of a card based on the first character. This function can change its implementation to affect all of places we need to use it - so, let's say you decide Jokers should be evaluated as 20, you can add it to that one function, and all of your code will now work with that new value. Thus, breaking apart our code into tiny functions that do one thing and are referenced for that one thing all over our codebase is important.

Categories

Resources