Var with range value without using array - javascript

I'm having trouble with this logic. I'm trying to find a way where a single variable will have multiple values without using array. Here is my code
var num = {
from: 500,
to: 700
};
if (num == 500 && num == 600 && num==700) {
console.log("working");
}
else {
console.log("not working")
}

You could take a function for checking the range.
function check({ from, to }, value) {
return from <= value && value <= to;
}
var num = { from: 100, to: 300 };
if (check(num, 500) && check(num, 600) && check(num, 700)) {
console.log("working");
} else {
console.log("not working")
}
console.log(check(num, 200));

Use a function and try comparing the values.
var num = {
from: 100,
to: 300,
checkValue:function(num){
return this.from <= num && num <= this.to
}
};
console.log('1st check');
if (num.checkValue(100) && num.checkValue(600) && num.checkValue(700)) {
console.log("working");
}
else {
console.log("not working")
}
console.log('2nd check');
if (num.checkValue(120) && num.checkValue(150) && num.checkValue(250)) {
console.log("working");
}
else {
console.log("not working")
}

To access your object (Variables with multiple values) you have to do like this :
var num = {
from: 100,
to: 300
}
console.log(num.from); //This will print 100
console.log(num.to); //This will print 300
and you can do this
num.from += 1;
console.log(num.from); //This will print 101
So your (Ryan Arellano) code must be like this :
function check(num, value) {
return num.from <= value && value <= num.to;
}
var num = { from: 100, to: 300 };
if (check(num, 500) && check(num, 600) && check(num, 700)) {
console.log("working");
} else {
console.log("not working")
}
console.log(check(num, 200));

Related

Appearing and Disappearing an array of images

I want to make images in assets called Leo + a number appearing and disappearing but it change images when the image is shown the half of the time, I don't understand why, i tried changing milliseconds but nothing
var counterForImages = 0
let leo = $("#Leo")
var photoAppearing = window.setInterval(function(){
var fadingIn = window.setInterval(function(){
leo.css("opacity", Number(leo.css("opacity"))+0.02)
if (leo.css("opacity") == 1) {
clearInterval(fadingIn)
}
}, 25)
var fadingOut = window.setInterval(function(){
leo.css("opacity", Number(leo.css("opacity"))-0.02)
if (leo.css("opacity") == 0) {
clearInterval(fadingOut)
}
}, 25)
leo.attr("src", "assets/Leo" + counterForImages%3 + ".png")
if (counterForImages%3 == 0) {
leo.css("width", "200px")
leo.css("left", "85%")
} else if (counterForImages%3 == 1) {
leo.css("width", "400px")
leo.css("left", "80%")
} else if (counterForImages%3 == 2) {
leo.css("width", "180px")
leo.css("left", "85%")
}
counterForImages++
}, 5000);
UPDATE
tried the following, does someone know how to avoid maximum recursion depth and do something forever?
var counterForImages = 1
let leo = $("#Leo")
async function delay(ms) {
// return await for better async stack trace support in case of errors.
return await new Promise(resolve => setTimeout(resolve, ms));
}
async function lol (fun) {
var fadingIn = window.setInterval(function(){
leo.css("opacity", Number(leo.css("opacity"))+0.02)
if (leo.css("opacity") == 1) {
clearInterval(fadingIn)
}
}, 50)
await delay(5000)
var fadingOut = window.setInterval(function(){
leo.css("opacity", Number(leo.css("opacity"))-0.02)
if (leo.css("opacity") == 0) {
clearInterval(fadingOut)
}
}, 50)
await delay(5000)
leo.attr("src", "assets/Leo" + counterForImages%3 + ".png")
if (counterForImages%3 == 0) {
leo.css("width", "200px")
leo.css("left", "85%")
} else if (counterForImages%3 == 1) {
leo.css("width", "400px")
leo.css("left", "80%")
} else if (counterForImages%3 == 2) {
leo.css("width", "180px")
leo.css("left", "85%")
}
counterForImages++
fun(lol)
}
lol(lol)
it looks like you are using jQuery, not pure JavaScript.
If I understand what you're doing, this might work:
var image_data=[[200,85], [400,80], [180,85]];
var counterForImages=0, leo=$('#leo');
function rotateImage() {
counterForImages=counterForImages%3;
leo.css({
opacity:0,
width:image_data[counterForImages][0]+'px',
left:image_data[counterForImage][1]+'%'
});
leo.attr('src', 'assets/Leo' + counterForImages + '.png');
leo.animate({opacity:1}, 5000, ()=>{
leo.animate({opacity:0}, 5000, ()=>{
counterForImages++;
rotateImage();
});
})
}

Javascript and Return Function

I am working on a lab for school and having a hard time getting a return value from another function. I think I am just missing one thing and cannot figure it out. The function is called from an HTML document and depending on the number inputted will return the letter grade. Below is my code:
function submitGradeForconversion() {
var numGradeElement = document.getElementById("numGrade");
var numGrade = Math.round(numGradeElement.value);
if (numGrade >= 0 && numGrade <= 100) {
document.getElementById("letterGrade").innerHTML = convertGrade(numGrade);
} else {
alert("Please enter a number between 0 and 100!")
}
}
function convertGrade(numGrade) {
if (numGrade >= 95) {
return numGrade(A);
}
}
The HTML is just a basic input box with a button to call the first function. Any assistance would be greatly appreciated. Thanks
function submitGradeForconversion() {
var numGradeElement = document.getElementById("numGrade");
var numGrade = Math.round(numGradeElement.value);
if (numGrade >= 0 && numGrade <= 100) {
document.getElementById("letterGrade").innerHTML = convertGrade(numGrade);
} else {
alert("Please enter a number between 0 and 100!")
}
}
function convertGrade(numGrade) {
if (numGrade >= 95) {
return "A";
}
if (numGrade >= 75) {
return "B";
}
if (numGrade >= 55) {
return "C";
}
if (numGrade >= 35) {
return "D";
}
if (numGrade >= 15) {
return "E";
} else{
return "F";
}
}
<input id="numGrade" onChange="submitGradeForconversion()" />
<div id="letterGrade">X</div>

Avoiding several nested if statements

I'm writing a function that pushes specific (predefined) variables to predefined arrays based on the status of 4 variables, all of which are ranging from 1 to 5 (they are the results of radio buttons pressed on our web page).
If the variables equal A, B, C and D, the predefined variables to predefined arrays X, Y and Z are defined by:
X = the combination of A and B.
Y = the combination of C and D.
Z = the combination of A, B, C and D.
Below is my realization of a solution to said problem (A, B, C and D are motivation, orientation, influence and relevance), using nested if/else statements. However, I find this solution inelegant. I both want to write cleaner code, and leave the code more readable for my fellow coworkers. What would be the most elegant way to type this out? Should I use functions, switch statements, something else?
Below is the entire function:
function getRadioParameters (influence, relevance, motivation, orientation) {
if (influence >= 3) {
if (relevance >= 3) {
influenceRelevanceArr.push(highInfluenceHighRelevance);
if (motivation >= 3) {
if (orientation >= 3) {
motivationOrientationArr.push(highMotivationHighOrientation);
stkImagesArr.push(getImage('HHHH'));
}
else if (orientation < 3) {
motivationOrientationArr.push(highMotivationLowOrientation);
stkImagesArr.push(getImage('HHHL'));
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with orientation. It is = ', orientation)
}
}
else if (motivation < 3) {
if (orientation >= 3) {
motivationOrientationArr.push(lowMotivationHighOrientation);
stkImagesArr.push(getImage('HHLH'));
}
else if (orientation<3) {
motivationOrientationArr.push(lowMotivationLowOrientation);
stkImagesArr.push(getImage('HHLL'));
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with orientation. It is = ', orientation);
}
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with motivation. It is = ', motivation);
}
}
else if (relevance < 3) {
influenceRelevanceArr.push(highInfluenceLowRelevance);
if (motivation >= 3) {
if (orientation >= 3) {
motivationOrientationArr.push(highMotivationHighOrientation);
stkImagesArr.push(getImage('HLHH'));
}
else if (orientation < 3) {
motivationOrientationArr.push(highMotivationLowOrientation);
stkImagesArr.push(getImage('HLHL'));
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with orientation. It is = ', orientation)
}
}
else if (motivation < 3) {
if (orientation >= 3) {
motivationOrientationArr.push(lowMotivationHighOrientation);
stkImagesArr.push(getImage('HLLH'));
}
else if (orientation<3) {
motivationOrientationArr.push(lowMotivationLowOrientation);
stkImagesArr.push(getImage('HLLL'));
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with orientation. It is = ', orientation);
}
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with motivation. It is = ', motivation);
}
}
else {
influenceRelevanceArr.push('');
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with relevance. It is =', relevance);
}
}
else if (influence < 3) {
if (relevance >= 3) {
influenceRelevanceArr.push(lowInfluenceHighRelevance);
if (motivation >= 3) {
if (orientation >= 3) {
motivationOrientationArr.push(highMotivationHighOrientation);
stkImagesArr.push(getImage('LHHH'));
}
else if (orientation < 3) {
motivationOrientationArr.push(highMotivationLowOrientation);
stkImagesArr.push(getImage('LHHL'));
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with orientation. It is = ', orientation)
}
}
else if (motivation < 3) {
if (orientation >= 3) {
motivationOrientationArr.push(lowMotivationHighOrientation);
stkImagesArr.push(getImage('LHLH'));
}
else if (orientation<3) {
motivationOrientationArr.push(lowMotivationLowOrientation);
stkImagesArr.push(getImage('LHLL'));
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with orientation. It is = ', orientation);
}
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with motivation. It is = ', motivation);
}
}
else if (relevance < 3) {
influenceRelevanceArr.push(lowInfluenceLowRelevance);
if (motivation >= 3) {
if (orientation >= 3) {
motivationOrientationArr.push(highMotivationHighOrientation);
stkImagesArr.push(getImage('LLHH'));
}
else if (orientation < 3) {
motivationOrientationArr.push(highMotivationLowOrientation);
stkImagesArr.push(getImage('LLHL'));
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with orientation. It is = ', orientation)
}
}
else if (motivation < 3) {
if (orientation >= 3) {
motivationOrientationArr.push(lowMotivationHighOrientation);
stkImagesArr.push(getImage('LLLH'));
}
else if (orientation<3) {
motivationOrientationArr.push(lowMotivationLowOrientation);
stkImagesArr.push(getImage('LLLL'));
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with orientation. It is = ', orientation);
}
}
else {
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with motivation. It is = ', motivation);
}
}
else {
influenceRelevanceArr.push('');
motivationOrientationArr.push('');
stkImagesArr.push('');
console.log('problem with relevance. It is =', relevance);
}
}
}
Thank you!
Here is an example of abstracting it away using a function:
//X = the combination of A and B.
//Y = the combination of C and D.
//Z = the combination of A, B, C and D.
// in this example:
// A > 5, B > 10, C> 15, D > 20
function returnCharacteristic(input) {
if (input[0] > 5 && input[1] > 10 && input[2] > 15 && input[3] > 20) {
return 'Z';
}
if (input[2] > 15 && input[3] > 20) {
return 'Y';
}
if (input[0] > 5 && input[1] > 10) {
return 'X';
}
return 'No criterea met';
}
let test1 = [10, 5, 33, 5];
let test2 = [10, 15, 32, 50];
let test3 = [20, 20, 10, 9];
let test4 = [0, 5, 50, 50];
console.log(returnCharacteristic(test1));
console.log(returnCharacteristic(test2));
console.log(returnCharacteristic(test3));
console.log(returnCharacteristic(test4));
In this example I used some random conditions to determine if a criteria was met but you of course need to tailor them to your needs. Usually when your code is deeply nested like yours you have made a code designing mistake. Usually there are more elegant solutions which require you to refactor the code a bit.
Deeply nesting code increases the difficulty of reasoning about it which not only makes your code less maintainable but also increases the chances of introducing bugs. And even when there are bugs it is harder to debug is deeply nested code.
Hopefully this was helpful.
If i understand what you're trying to do right, i think you can do something like this
var obj = {
"highInfluence_highRelevance": highInfluenceHighRelevance,
"highInfluence_lowRelevance": highInfluenceLowRelevance,
"lowInfluence_highRelevance": lowInfluenceHighRelevance,
"lowInfluence_lowRelevance": lowInfluenceLowRelevance,
"highMotivation_highOrientation": highMotivationHighOrientation,
"highMotivation_lowOrientation": highMotivationLowOrientation,
"lowMotivation_highOrientation": lowMotivationHighOrientation,
"lowMotivation_lowOrientation": lowMotivationLowOrientation
}
var imgStr = "";
function evaluateRadioParameters(num) {
if (num >= 3) return "high";
else if (num < 3) return "low";
return "";
}
function setimgStr(num, str) {
if (num >= 3) imgStr += "H";
else if (num < 3) imgStr += "L";
else console.log('problem with ' + str + '. It is = ', num);
}
function getRadioParameters(influence, relevance, motivation, orientation) {
var influenceStr = evaluateRadioParameters(influence);
var relevanceStr = evaluateRadioParameters(relevance);
var motivationStr = evaluateRadioParameters(motivation);
var orientationStr = evaluateRadioParameters(orientation);
if (influenceStr == "" || relevanceStr == "") {
influenceRelevanceArr.push("");
} else {
influenceRelevanceArr.push(obj[influenceStr + "Influence_" + relevanceStr + "Relevance"]);
}
if (motivationStr == "" || orientationStr == "") {
motivationOrientationArr.push("");
} else {
motivationOrientationArr.push(obj[influenceStr + "Influence_" + relevanceStr + "Relevance"]);
}
if (influenceStr == "" || relevanceStr == "" || motivationStr == "" || orientationStr == "")
stkImagesArr.push('');
else {
setimgStr(influence, "influence");
setimgStr(relevance, "relevance");
setimgStr(motivation, "motivation");
setimgStr(orientation, "orientation");
stkImagesArr.push(getImage(imgStr));
}
}
It might be easier to get each individual value separately, then combine them somehow - it all depends on your data structures. From what I see so far, I think you can do something like this (this is high level, you'll have to fill in the full details yourself):
function getRadioParameters(influence, relevance, motivation, orientation) {
const inf = gague(influence, 'highInfluence', 'lowInfluence');
const rel = gague(relevance, 'highRelevance', 'lowRelevance');
const mot = gague(motivation, 'highMotivation', 'lowMotivation');
const ori = gague(orientation, 'highOrientation', 'lowOrientation');
const allVals = [inf, rel, mot, ori];
const finalValues = getFinalValues(allVals);
return finalValues;
}
function getFinalValues(allVals) {
const finalValues = { img: '', char: '' };
allVals.forEach(function(item) {
finalValues.img += item.img;
finalValues.char += item.char;
});
return finalValues;
}
function gague(param, high, low) {
if (param >= 3) return { char: high, img: 'H' };
return { char: low, img: 'L' };
}
let result = getRadioParameters(3, 3, 3, 3);
console.log(result);
result = getRadioParameters(3, 3, 3, 0);
console.log(result);
result = getRadioParameters(3, 3, 0, 3);
console.log(result);
result = getRadioParameters(3, 0, 3, 3);
console.log(result);
also, if you're using ES6/7 you can simplify the code even more:
function getRadioParameters(influence, relevance, motivation, orientation) {
const inf = gague(influence, 'HIGH-influence', 'LOW-influence');
const rel = gague(relevance, 'HIGH-relevance', 'LOW-relevance');
const mot = gague(motivation, 'HIGH-motivation', 'LOW-motivation');
const ori = gague(orientation, 'HIGH-orientation', 'LOW-orientation');
const allVals = [inf, rel, mot, ori];
const finalValue = allVals.reduce(getFinalValue, { img: '', char: '' });
return finalValue;
}
function getFinalValue(prev, current) {
const img = prev.img + current.img;
const char = prev.char + ' ' + current.char;
return { img, char };
}
function gague(param, high, low) {
if (param >= 3) return { char: high, img: 'H' };
return { char: low, img: 'L' };
}
let result = getRadioParameters(3, 3, 3, 3);
console.log(result);
result = getRadioParameters(3, 3, 3, 0);
console.log(result);
result = getRadioParameters(3, 3, 0, 3);
console.log(result);
result = getRadioParameters(3, 0, 3, 3);
console.log(result);

Passing string to javascript function results in value

Something really odd going on here, and I have gone round in circles trying to figure out what is going on...I have a couple of input boxes, with onchange events firing for them, the event being loaded with a JS function that takes the value ( name of another item ) and actions the function accordingly. Only thing is, when the value of the string arrives at the other function, it has somehow been assigned a numeric value, specifically that of the input box.
My php that helps build the form:
$filterfield = '"p_delweek"';
print "<span class='filter'>Del Week<input class='menulink spin-button' id='weekno' type='text' value='".$weekno."' onKeyUp='doFilter($filterfield)' onChange='doFilter($filterfield)' data-filtered='0'/><input type='button' value='Clear' onClick='doUnfilter()'></span>";
$filterfield = '"p_seedweek"';
print "<span class='filter'>Sow Week<input class='menulink spin-button' id='sowweekno' type='text' value='".$weekno."' onKeyUp='doFilter($filterfield)' onChange='doFilter($filterfield)' data-filtered='0'/><input type='button' value='Clear' onClick='doUnfilter()'></span>";
Resulting HTML in source:
<span class="filter">Del Week<input style="width: 50px; height: 22px;" class="menulink spin-button smartspinner" id="weekno" value="26" onkeyup='doFilter("p_delweek")' onchange='doFilter("p_delweek")' data-filtered="0" type="text"><input value="Clear" onclick="doUnfilter()" type="button"></span><span class="filter">Sow Week<input style="width: 50px; height: 22px;" class="menulink spin-button smartspinner" id="sowweekno" value="26" onkeyup='doFilter("p_seedweek")' onchange='doFilter("p_seedweek")' data-filtered="0" type="text"><input value="Clear" onclick="doUnfilter()" type="button"></span>
Javascript function that is called:
function doFilter(filterfield) {
console.log("DoFilter:"+filterfield);
var filterInfo=[
{
fieldName : filterfield,
logic : "equal",
value : Sigma.Util.getValue("weekno")
}
]
// the next lines action the filtering
var grid=Sigma.$grid("myGrid1");
console.log("filterinfo="+filterInfo);
var rowNOs=grid.applyFilter(filterInfo);
}
It all goes fine until we get to the console.log("DoFilter:"+filterfield) , which results in DoFilter:25; 25 happens to be the value of the input box.
How is it grabbing that value? How to pass the real one?
TBH — I'm not sure if I got what you're after. However, if you must call a function inline (I recommend that you don’t), you can pass a reference to the input field as parameter and make it available in the methods’s body:
<input onchange="doFilter('p_delweek', this)" type="text">
​
function doFilter(filterfield, field) {
console.log(filterfield);
// field is a reference to the input field, hence
console.log(field.value);
// will print the current value for this field
}
This is not the answer, this file is the problem:
(function($) {
$.fn.extend({
spinit: function(options) {
var settings = $.extend({ min: 0, max: 100, initValue: 0, callback: doFilter, stepInc: 1, pageInc: 10, width: 50, height: 15, btnWidth: 10, mask: '' }, options);
return this.each(function() {
var UP = 38;
var DOWN = 40;
var PAGEUP = 33;
var PAGEDOWN = 34;
var mouseCaptured = false;
var mouseIn = false;
var interval;
var direction = 'none';
var isPgeInc = false;
var value = Math.max(settings.initValue, settings.min);
var el = $(this).val(value).css('width', (settings.width) + 'px').css('height', settings.height + 'px').addClass('smartspinner');
raiseCallback(value);
if (settings.mask != '') el.val(settings.mask);
$.fn.reset = function(val) {
if (isNaN(val)) val = 0;
value = Math.max(val, settings.min);
$(this).val(value);
raiseCallback(value);
};
function setDirection(dir) {
direction = dir;
isPgeInc = false;
switch (dir) {
case 'up':
setClass('up');
break;
case 'down':
setClass('down');
break;
case 'pup':
isPgeInc = true;
setClass('up');
break;
case 'pdown':
isPgeInc = true;
setClass('down');
break;
case 'none':
setClass('');
break;
}
}
el.focusin(function() {
el.val(value);
});
el.click(function(e) {
mouseCaptured = true;
isPgeInc = false;
clearInterval(interval);
onValueChange();
});
el.mouseenter(function(e) {
el.val(value);
});
el.mousemove(function(e) {
if (e.pageX > (el.offset().left + settings.width) - settings.btnWidth - 4) {
if (e.pageY < el.offset().top + settings.height / 2)
setDirection('up');
else
setDirection('down');
}
else
setDirection('none');
});
el.mousedown(function(e) {
isPgeInc = false;
clearInterval(interval);
interval = setTimeout(onValueChange, 250);
});
el.mouseup(function(e) {
mouseCaptured = false;
isPgeInc = false;
clearInterval(interval);
});
el.mouseleave(function(e) {
setDirection('none');
if (settings.mask != '') el.val(settings.mask);
}); el.keydown(function(e) {
switch (e.which) {
case UP:
setDirection('up');
onValueChange();
break; // Arrow Up
case DOWN:
setDirection('down');
onValueChange();
break; // Arrow Down
case PAGEUP:
setDirection('pup');
onValueChange();
break; // Page Up
case PAGEDOWN:
setDirection('pdown');
onValueChange();
break; // Page Down
default:
setDirection('none');
break;
}
});
el.keyup(function(e) {
setDirection('none');
});
el.keypress(function(e) {
if (el.val() == settings.mask) el.val(value);
var sText = getSelectedText();
if (sText != '') {
sText = el.val().replace(sText, '');
el.val(sText);
}
if (e.which >= 48 && e.which <= 57) {
var temp = parseFloat(el.val() + (e.which - 48));
if (temp >= settings.min && temp <= settings.max) {
value = temp;
raiseCallback(value);
}
else {
e.preventDefault();
}
}
});
el.blur(function() {
if (settings.mask == '') {
if (el.val() == '')
el.val(settings.min);
}
else {
el.val(settings.mask);
}
});
el.bind("mousewheel", function(e) {
if (e.wheelDelta >= 120) {
setDirection('down');
onValueChange();
}
else if (e.wheelDelta <= -120) {
setDirection('up');
onValueChange();
}
e.preventDefault();
});
if (this.addEventListener) {
this.addEventListener('DOMMouseScroll', function(e) {
if (e.detail > 0) {
setDirection('down');
onValueChange();
}
else if (e.detail < 0) {
setDirection('up');
onValueChange();
}
e.preventDefault();
}, false);
}
function raiseCallback(val) {
if (settings.callback != null) settings.callback(val);
}
function getSelectedText() {
var startPos = el.get(0).selectionStart;
var endPos = el.get(0).selectionEnd;
var doc = document.selection;
if (doc && doc.createRange().text.length != 0) {
return doc.createRange().text;
} else if (!doc && el.val().substring(startPos, endPos).length != 0) {
return el.val().substring(startPos, endPos);
}
return '';
}
function setValue(a, b) {
if (a >= settings.min && a <= settings.max) {
value = b;
} el.val(value);
}
function onValueChange() {
if (direction == 'up') {
value += settings.stepInc;
if (value > settings.max) value = settings.max;
setValue(parseFloat(el.val()), value);
}
if (direction == 'down') {
value -= settings.stepInc;
if (value < settings.min) value = settings.min;
setValue(parseFloat(el.val()), value);
}
if (direction == 'pup') {
value += settings.pageInc;
if (value > settings.max) value = settings.max;
setValue(parseFloat(el.val()), value);
}
if (direction == 'pdown') {
value -= settings.pageInc;
if (value < settings.min) value = settings.min;
setValue(parseFloat(el.val()), value);
}
raiseCallback(value);
}
function setClass(name) {
el.removeClass('up').removeClass('down');
if (name != '') el.addClass(name);
}
});
}
});
})(jQuery);
Why and where does this alter the passing value of a function attached to the < INPUT > ?

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

Categories

Resources