convert nested if statements to more elegant switch? - javascript

how can i convert this nested if statement to something more readable and 'elegant'?
if(speed==0){
othvalue=0;
}else {
if(speed>value1864cmn){
othvalue=value1864cmn;
}else {
if(speed>value1746cmn){
othvalue=value1746cmn;
}else {
if(speed>value1628cmn){
othvalue=value1628cmn;
}else {
if(speed>value1510cmn){
othvalue=value1510cmn;
}else {
if(speed>value1392cmn){
othvalue=value1392cmn;
}else {
if(speed>value1274cmn){
othvalue=value1274cmn;
}else {
if(speed>value1156cmn){
othvalue=value1156cmn;
}else {
if(speed>value1038cmn){
othvalue=value1038cmn;
}else {
if(speed>value920cmn){
othvalue=value920cmn;
}
}
}
}
}
}
}
}
}
};

You can use "match" construct:
var othvalue = (speed == 0) ? 0
: (speed <= 10) ? 10
: (speed <= 20) ? 20
: (speed <= 30) ? 30
: 40;

You don't need to nest this, nor convert it to a switch statement. Just put the if right next to the else.
For instance:
if(speed==0){
othvalue=0;
} else if(speed>value1864cmn){
othvalue=value1864cmn;
} else if {
...

if (speed == 0) {
othvalue = 0;
} else if (speed > value1864cmn) {
othvalue = value1864cmn;
} else if (speed > value1746cmn) {
othvalue = value1746cmn;
} else if (speed > value1628cmn) {
othvalue = value1628cmn;
} else if (speed > value1510cmn) {
othvalue = value1510cmn;
} else if (speed > value1392cmn) {
othvalue = value1392cmn;
} else if (speed > value1274cmn) {
othvalue = value1274cmn;
} else if (speed > value1156cmn) {
othvalue = value1156cmn;
} else if (speed > value1038cmn) {
othvalue = value1038cmn;
} else if (speed > value920cmn) {
othvalue = value920cmn;
};

if (speed == 0) {
othvalue = 0;
} else {
var values = [
value1746cmn, value1628cmn, value1510cmn, value1392cmn, value1274cmn,
value1156cmn, value1038cmn, value920cmn
];
for (var i in values) {
if (speed > values[i]) {
othvalue = values[i];
break;
}
}
}

// I don't know about elegant, but stepping through an array is pretty quick.
function setSpeedValue(speed){
var L= 9, values= [0, 920, 1038, 1156, 1274, 1392, 1510, 1628, 1746, 1864];
while(values[L]>speed)--L;
return 'value'+values[L]+'cmn';
}
alert(setSpeedValue(1040))

Related

Same code for multiple functions, how do I shorten this?

I've created 3 functions: for 3 health bars I made. These functions actually have the same code, so I want to shorten these. I tried to make an general function with parameters and then call the function. But I don't know what to write in this general function to make all the three health bars work.
Sorry if it sounds a little vague. Hope someone can help.
Seem like the only different between 3 functions total and id, you can create generalFunction and call it in each function as below.
function generalFunction(total,id) {
if (total >= 100) {
document.getElementById("id").value = total--;
} else if ((total <= 100) && (total >= 80)) {
document.getElementById("id").value = total--;
} else if ((total <= 80) && (total >= 60)) {
document.getElementById("id").value = total--;
} else if ((total <= 60) && (total >= 40)) {
document.getElementById("id").value = total--;
document.getElementById("status-tamagotchi").src = document.getElementById("status-tamagotchi").src = "images/monster-state-3-v2.gif";
} else if ((total <= 40) && (total >= 20)) {
document.getElementById("id").value = total--;
} else if ((total <= 20) && (total > 0)) {
document.getElementById("id").value = total--;
} else if (total == 0) {
document.getElementById("status-tamagotchi").src = document.getElementById("status-tamagotchi").src = "images/monster-state-5-v1.gif";
}
}
function hungerFunction() {
generalFunction(hungerTotal,"meter-hunger")
}
function thirstFunction() {
generalFunction(thirstTotal,"meter-thirst")
}
function funFunction() {
generalFunction(funTotal,"meter-fun")
}
Firstly, why you have so many else if when the code is the same ? You should regroups your intervals, why you only have 20 length intervals ?
You can also regroup the same logic under a function like this one below.
function globalFunction(value, id) {
if (value > 0) {
document.getElementById(id).value = value--;
} else {
document.getElementById("status-tamagotchi").src = "images/monster-state-5-v1.gif";
}
if (value >= 40 && value <= 60) {
document.getElementById("status-tamagotchi").src = "images/monster-state-3-v2.gif";
}
}
function hungerFunction() {
globalFunction(hungerTotal, "meter-hunger")
}
function thirstFunction() {
globalFunction(thirstTotal, "meter-thirst")
}
function funFunction() {
globalFunction(funTotal, "meter-fun")
}
Avoiding repetition means identifying the common elements in each repetitive section, and extracting those into a separate function. Those parts which are different between each repetitive section should be either handled outside of the function, or made parameters into the function.
In this case, the common elements seem to be everything except for the element ID ("meter-hunger", "meter-thirst", "meter-fun") and the variable being used (hungerTotal, thirstTotal, funTotal). So, make those two parts parameters into a new function, and call that new function instead.
function drainStatus(id,stat) {
if (stat >= 100) {
document.getElementById(id).value = stat--;
} else if ((stat <= 100) && (stat >= 80)) {
document.getElementById(id).value = stat--;
} else if ((stat <= 80) && (stat >= 60)) {
document.getElementById(id).value = stat--;
} else if ((stat <= 60) && (stat >= 40)) {
document.getElementById(id).value = stat--;
document.getElementById("status-tamagotchi").src = document.getElementById("status-tamagotchi").src = "images/monster-state-3-v2.gif";
} else if ((stat <= 40) && (stat >= 20)) {
document.getElementById(id).value = stat--;
} else if ((stat <= 20) && (stat > 0)) {
document.getElementById(id).value = stat--;
} else if (stat == 0) {
document.getElementById("status-tamagotchi").src = document.getElementById("status-tamagotchi").src = "images/monster-state-5-v1.gif";
}
}
There is one issue you run into with this: Passing any of the _Total variables into this function will pass by value, so modifying the stat parameter won't modify the outer variable. To fix this I would just have the function return the new value, and make the caller responsible for assigning it back.
function drainStatus(id,stat) {
if (stat >= 100) {
document.getElementById(id).value = stat--;
} else if ((stat <= 100) && (stat >= 80)) {
document.getElementById(id).value = stat--;
} else if ((stat <= 80) && (stat >= 60)) {
document.getElementById(id).value = stat--;
} else if ((stat <= 60) && (stat >= 40)) {
document.getElementById(id).value = stat--;
document.getElementById("status-tamagotchi").src = document.getElementById("status-tamagotchi").src = "images/monster-state-3-v2.gif";
} else if ((stat <= 40) && (stat >= 20)) {
document.getElementById(id).value = stat--;
} else if ((stat <= 20) && (stat > 0)) {
document.getElementById(id).value = stat--;
} else if (stat == 0) {
document.getElementById("status-tamagotchi").src = document.getElementById("status-tamagotchi").src = "images/monster-state-5-v1.gif";
}
return stat;
}
setInterval(function() {
hungerTotal = drainStatus("meter-hunger",hungerTotal);
thirstTotal = drainStatus("meter-thirst",thirstTotal);
funTotal = drainStatus("meter-fun",funTotal);
}, 300);
If you're wanting to avoid repetition there's one more thing you can do here. Notice that every single one of your if-statements results in the exact same line, except for if (stat == 0)... so you can just invert this, and execute that line if stat is != 0.
function drainStatus(id,stat) {
if (stat > 0) {
document.getElementById(id).value = stat--;
}
if ((stat <= 60) && (stat >= 40)) {
document.getElementById("status-tamagotchi").src = document.getElementById("status-tamagotchi").src = "images/monster-state-3-v2.gif";
} else if (stat == 0) {
document.getElementById("status-tamagotchi").src = document.getElementById("status-tamagotchi").src = "images/monster-state-5-v1.gif";
}
return stat;
}
Just make decision using function argument like this:
function myallfunctions(arg) {
document.getElementById(arg).value = 70;
}
myallfunctions("input1");
<input type="text" id="input1"/>
Also you need study about functions.

Javascript injection add item to basket

I am trying to run this script which effectively goes through a json list that contains url and a size to go to the link set add the item to cart based on size, check if it is in stock or already added. I have got the link and the size searching algorithms work independently but together they seem to not work and I can't figure out why?
var foundall = false;
var copItems = [{
"url": "https://www.supremenewyork.com/mobile/#products/303518/22745",
"size": "Medium"
}];
for (var i = 0; i < copItems.length; i++) {
AddToCart(copItems[i], function(carted) {
console.log(carted);
});
}
function AddToCart(item, callback) {
location.href = item.url;
var counter = 0;
var waitToAppear = setInterval(function() {
if (document.querySelector('#cart-update > span')) {
if (document.querySelector('#cart-update > span').innerHTML == 'remove') {
return callback("failed");
clearInterval(waitToAppear);
} else if (document.querySelector('#cart-update > span').innerHTML == 'sold out') {
copSelectSize(size, function(data) {
return callback(data);
clearInterval(waitToAppear);
});
} else if (document.querySelector('#cart-update > span').innerHTML == 'add to basket') {
copSelectSize(item.size, function(Sized) {
return callback("failed");
clearInterval(waitToAppear);
})
} else {
counter += 1;
if (counter == 5) {
return callback("failed");
clearInterval(waitToAppear);
}
}
}
}, 100);
}
function copSelectSize(size, callback) {
var counter = 0;
var checkExist = setInterval(function() {
if (document.getElementById('size-options').length) {
var sizes = document.getElementById('size-options').options;
var size_id;
for (var i = 0; i < sizes.length; i++) {
if (sizes[i].innerText == '\(Size)') {
size_id = i;
document.getElementById('size-options').selectedIndex = size_id;
document.getElementById('size-options-link').innerHTML = '\(Size)';
if (document.querySelector('#cart-update > span').innerHTML != 'remove') {
document.querySelector('#cart-update > span').click();
return callback("success");
clearInterval(checkExist);
}
var checkExista = setInterval(function() {
if (document.querySelector('#cart-update > span').innerHTML == 'remove') {
checkExista = '';
}
clearInterval(checkExista);
}, 100);
break;
}
}
}
counter += 1;
if (counter == 5) {
return callback("failed");
clearInterval(checkExist);
}
}, 200);
}

Betfair like Odds increment and decrement

Please help me it is very irritating. Don't know why my logic is failed every time.
I am trying to make Betfair like odds increment in my web project. Betfair have it's own price group which can be found here
LINK: https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/Betfair+Price+Increments
Here is explanation:
if odds is 1.01 and some body want to increase that odds via html5 number spinner the increment will be 0.01 and if odds is 2 the increment will be 0.02. whole increment list is available in that link.
working example can be found in betfair's betslip.
here is my Javascript:
function getIncremantal(fval) {
var val = parseFloat(fval);
var step;
if (val <= 1.99) {
step = 0.01;
} else if (val > 2 && val < 3) {
step = 0.02;
} else if (val > 3 && val < 4) {
step = 0.05;
} else if (val > 4 && val < 6) {
step = 0.1;
} else if (val > 6 && val < 10) {
step = 0.2;
} else if (val > 10 && val < 19.5) {
step = 0.5;
} else if (val >= 20 && val < 30) {
step = 1;
} else if (val >= 30 && val < 50) {
step = 2;
} else if (val >= 50 && val < 100) {
step = 5;
} else if (val >= 100 && val < 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}
Update: jsFiddle
http://jsfiddle.net/71fs0a67/1/
I tried the following which is not using number stepping, but if you use the buttons it does work. It is an alternate solution, sorry if its not what you are looking for.
HTML:
<input type="number" min="1.01" max="1000" id="num"/>
<button class="increment">+</button>
<button class="decrement">-</button>
Javascript:
$('.increment').on('click', function() {
var elem = $('#num');
var value = parseFloat(elem.val());
var result = +(value + getIncremantal(value)).toFixed(2);
elem.val(result);
});
$('.decrement').on('click', function() {
var elem = $('#num');
var value = parseFloat(elem.val());
var result = +(value - getDecremantal(value)).toFixed(2);
elem.val(result);
});
function getIncremantal(val) {
var step;
if (val < 2) {
step = 0.01;
} else if (val >= 2 && val < 3) {
step = 0.02;
} else if (val >= 3 && val < 4) {
step = 0.05;
} else if (val >= 4 && val < 6) {
step = 0.1;
} else if (val >= 6 && val < 10) {
step = 0.2;
} else if (val >= 10 && val < 20) {
step = 0.5;
} else if (val >= 20 && val < 30) {
step = 1;
} else if (val >= 30 && val < 50) {
step = 2;
} else if (val >= 50 && val < 100) {
step = 5;
} else if (val >= 100 && val < 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}
function getDecremantal(val) {
var step;
if (val <= 2) {
step = 0.01;
} else if (val > 2 && val <= 3) {
step = 0.02;
} else if (val > 3 && val <= 4) {
step = 0.05;
} else if (val > 4 && val <= 6) {
step = 0.1;
} else if (val > 6 && val <= 10) {
step = 0.2;
} else if (val > 10 && val <= 20) {
step = 0.5;
} else if (val > 20 && val <= 30) {
step = 1;
} else if (val > 30 && val <= 50) {
step = 2;
} else if (val > 50 && val <= 100) {
step = 5;
} else if (val > 100 && val <= 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}
http://jsfiddle.net/71fs0a67/7/
With jquery ui spinner, you can do something like this:
$( "#spinner" ).spinner({
min: 1.01,
max: 1000,
step: 0.01,
spin: function( event, ui ) {
event.preventDefault();
event.stopPropagation();
var value = this.value || ui.value;
value = parseFloat(value);
var step;
if ($(event.currentTarget).hasClass('ui-spinner-up')) {
step = getIncremantal(value);
value = +(value + step).toFixed(2);
$( "#spinner" ).spinner('value', value);
} else {
step = getDecremantal(value);
value = +(value - step).toFixed(2);
$( "#spinner" ).spinner('value', value);
}
}
});
http://jsfiddle.net/71fs0a67/9/
Your code will return undefined for whole numbers.
Change all instances of val > number to val >= number
Try this:
function getIncremantal(fval) {
var val = parseFloat(fval);
var step;
if (val < 2) {
step = 0.01;
} else if (val >= 2 && val < 3) {
step = 0.02;
} else if (val >= 3 && val < 4) {
step = 0.05;
} else if (val >= 4 && val < 6) {
step = 0.1;
} else if (val >= 6 && val < 10) {
step = 0.2;
} else if (val >= 10 && val < 20) {
step = 0.5;
} else if (val >= 20 && val < 30) {
step = 1;
} else if (val >= 30 && val < 50) {
step = 2;
} else if (val >= 50 && val < 100) {
step = 5;
} else if (val >= 100 && val < 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}
function getDecremantal(fval) {
var val = parseFloat(fval);
var step;
if (val <= 2) {
step = 0.01;
} else if (val > 2 && val <= 3) {
step = 0.02;
} else if (val > 3 && val <= 4) {
step = 0.05;
} else if (val > 4 && val <= 6) {
step = 0.1;
} else if (val > 6 && val <= 10) {
step = 0.2;
} else if (val > 10 && val <= 20) {
step = 0.5;
} else if (val > 20 && val <= 30) {
step = 1;
} else if (val > 30 && val <= 50) {
step = 2;
} else if (val > 50 && val <= 100) {
step = 5;
} else if (val > 100 && val <= 1000) {
step = 10;
} else if (val > 1000) {
step = null;
}
return step;
}

Can anyone help me correctly define a function in JS?

I have created a button with HTML and am trying to run a function I programmed with JavaScript. I cannot get the function to work and receive the error message:
reference error: myFunction is not defined
Here is my code. Can anyone help me define this function?
....<button type="button" onclick="myFunction(shot)">...
<script lang="JavaScript">
var shot = Math.random();
if (shot < .001) {
shot = 1;
} else if (shot < .18) {
shot = 2;
} else if (shot < .5) {
shot = 3;
} else if (shot < .84) {
shot = 4;
} else if (shot < .94) {
shot = 5;
} else if (shot < .991) {
shot = 6;
} else {
shot = 7;
};
function myFunction(x) {
if (x === 1) {
console.log("-2");
} else if (x === 2) {
console.log("-1");
} else if (x === 3) {
console.log("0");
} else if (x === 4) {
console.log("+1");
} else if (x === 5) {
console.log("+2");
} else if (x === 6) {
console.log("+3");
} else {
console.log("+4");
}
};
</script>
That is most likely because the script is after your <button> in your HTML. Place it above and everything should be fine.
Because your button is before your script the button doesn't know your function. When you press your button the function ins't defined yet. You have to place your script for the button.
Also it would be better to put type="text/javascript" in your <script> tag.
Your script would be like this:
<script type="text/javascript">
var shot = Math.random();
if (shot < .001) {
shot = 1;
} else if (shot < .18) {
shot = 2;
} else if (shot < .5) {
shot = 3;
} else if (shot < .84) {
shot = 4;
} else if (shot < .94) {
shot = 5;
} else if (shot < .991) {
shot = 6;
} else {
shot = 7;
};
function myFunction(x) {
if (x === 1) {
console.log("-2");
} else if (x === 2) {
console.log("-1");
} else if (x === 3) {
console.log("0");
} else if (x === 4) {
console.log("+1");
} else if (x === 5) {
console.log("+2");
} else if (x === 6) {
console.log("+3");
} else {
console.log("+4");
}
};
</script>
<button type="button" onclick="myFunction(shot)">
I'd do this using jQuery:
var shot;
$(document).ready(function () {
shot = Math.random();
if (shot < 0.001) {
shot = 1;
} else if (shot < 0.18) {
shot = 2;
} else if (shot < 0.5) {
shot = 3;
} else if (shot < 0.84) {
shot = 4;
} else if (shot < 0.94) {
shot = 5;
} else if (shot < 0.991) {
shot = 6;
} else {
shot = 7;
}
});
$("#myButton").click(function () {
var x = shot;
if (x === 1) {
console.log("-2");
} else if (x === 2) {
console.log("-1");
} else if (x === 3) {
console.log("0");
} else if (x === 4) {
console.log("+1");
} else if (x === 5) {
console.log("+2");
} else if (x === 6) {
console.log("+3");
} else {
console.log("+4");
}
});
With your button as so:
<button id="myButton" type="button">Test</button>
Demo here
With this, however, your result is going to be the same per page load unless you do the calculation for 'shot' in the click function!
I believe it is the call to your button onClick method that makes the problem.
<button type="button" onclick="myFunction(shot)">
At that point in code the shot variable is not defined.
You need to first declare the variable before usage. Or better yet remove it from button call and defined it in your myFunction as below:
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getShot() {
return getRandomInt(1, 7);
}
function myFunction() {
var x = getShot();
if (x === 1) {
console.log("-2");
} else if (x === 2) {
console.log("-1");
} else if (x === 3) {
console.log("0");
} else if (x === 4) {
console.log("+1");
} else if (x === 5) {
console.log("+2");
} else if (x === 6) {
console.log("+3");
} else {
console.log("+4");
}
};
</script>
You could either put the code before the button
or
Make the script to execute after the DOM loads by using
document.addEventListener("DOMContentLoaded", function(event) {
//put your function here
});
Also, a good practice (separation of concern), is to not have have the function call on the html. Instead you could add an event listener in your javascript.
document.getElementById("myButton").addEventListener("click", function(){
// your function here
});

Uploading bar is not syncing with actual progress. what should i do?

Below is my code:
<script type="text/javascript">
window.onload = function ()
{
hideProgress();
}
function showProgress()
{
$(function ()
{
$("#dialog-modal").dialog(
{
height: 70,`
width: 450,
modal: true,
resizable: false
});
$(".ui-dialog-titlebar").hide();
$("#progressbar").progressbar({
value: 0
});
});
updateProgessBar();
}
function hideProgress()
{
$("#dialog-modal").dialog('close');
}
function updateProgessBar() {
var currentProgress = $("#progressbar").progressbar("value");
currentProgress = currentProgress + 2;
$("#progressbar").progressbar("value", currentProgress);
if (currentProgress < 10) {
var temp = setTimeout("updateProgessBar();", 500);
}
else if (currentProgress >= 10 && currentProgress < 30) {
var temp = setTimeout("updateProgessBar();", 1000);
}
else if (currentProgress >= 30 && currentProgress < 45) {
var temp = setTimeout("updateProgessBar();", 1500);
}
else if (currentProgress >= 45 && currentProgress < 60) {
var temp = setTimeout("updateProgessBar();", 2000);
}
else if (currentProgress >= 60 && currentProgress < 80) {
var temp = setTimeout("updateProgessBar();", 2500);
}
else if (currentProgress >= 80 && currentProgress < 95) {
var temp = setTimeout("updateProgessBar();", 3000);
}
else if (currentProgress >= 95) {
}
}
function CheckValidation() {
if (Page_ClientValidate()) {
// Call Your custom JS function and return value.
showProgress();
return true;
}
else {
return false;
}
}
</script>

Categories