Javascript Function Parameter Update - javascript

I am running into a problem here trying to create a product showcase. Here is my Javascript code: http://codeshare.io/MeJQi
The slider for this code is for is here live at: http://therrd.com/screening.html#tenant-Screening
I can land on this specific page in two ways. One way is a button on another page that changes the default FROM of the slider to land on 15 Units which shows "Product25". Then the other way of landing on this page is where the slider is on default start value of 30 Unit and shows "Product1".
The problem I am having is changing the default product when I land on this page by clicking on the button on the other page, the slider updates but the showing product does not.
I would like to change the default value for the showProduct() based on the slider.
<script>
$(function() {
init();
});
function init()
{
hideAllProducts();
showProduct(1);
vals = {max: 2000, min: 1, def: 20} //use your own values here for max min and def
var param = window.location.href.split("slide=");
slide = isNaN(param[param.length - 1]) ||
param[param.length - 1] > vals.max ||
param[param.length - 1] < vals.min ? vals.def : param[param.length - 1];
//check if there is a url param, if it's a number and if it's in range
$("#screeningSlider").ionRangeSlider({
hide_min_max: true,
keyboard: true,
from: slide,
min: 1,
max: 2000,
step: 0,
grid_num: 4,
prettify_separator: ",",
postfix: " Units",
max_postfix: "+",
force_edges: true,
onStart: function (value) {
document.getElementById("value").innerHTML = (value.from);
},
onChange: function (value) {
document.getElementById("value").innerHTML = (value.from);
},
onFinish: function (value) {
document.getElementById("value").innerHTML = (value.from);
},
onUpdate: function (value) {
document.getElementById("value").innerHTML = (value.from);
}
});
$("#screeningSlider").on("change", function () {
var $this = $(this),
value = $this.prop("value");
productSliderOnChange(value);
});
}
function productSliderOnChange(value)
{
$("#value").text(value);
if(value == 0)
hideAllProducts();
else if ((value > 0) && (value <= 20))
{
hideAllProducts();
showProduct(25);
}
else if ((value >= 21) && (value <= 60))
{
hideAllProducts();
showProduct(1);
}
else if ((value >= 61) && (value <= 120))
{
hideAllProducts();
showProduct(2);
}
else if ((value >= 121) && (value <= 180))
{
hideAllProducts();
showProduct(3);
}
else if ((value >= 181) && (value <= 360))
{
hideAllProducts();
showProduct(4);
}
else if ((value >= 361) && (value <= 580))
{
hideAllProducts();
showProduct(5);
}
else if ((value >= 581) && (value <= 780))
{
hideAllProducts();
showProduct(6);
}
else if ((value >= 781) && (value <= 980))
{
hideAllProducts();
showProduct(7);
}
else if ((value >= 981) && (value <= 1180))
{
hideAllProducts();
showProduct(8);
}
else if ((value >= 1181) && (value <= 1380))
{
hideAllProducts();
showProduct(9);
}
else if ((value >= 1381) && (value <= 1580))
{
hideAllProducts();
showProduct(10);
}
else if ((value >= 1581) && (value <= 1780))
{
hideAllProducts();
showProduct(11);
}
else if ((value >= 1781) && (value <= 1980))
{
hideAllProducts();
showProduct(12);
}
else if ((value > 1981))
{
hideAllProducts();
showProduct(13);
}
else {
hideAllProducts();
showProduct(1);
}
}
function hideAllProducts()
{
$("#Product25").hide();
$("#Product1").hide();
$("#Product2").hide();
$("#Product3").hide();
$("#Product4").hide();
$("#Product5").hide();
$("#Product6").hide();
$("#Product7").hide();
$("#Product8").hide();
$("#Product9").hide();
$("#Product10").hide();
$("#Product11").hide();
$("#Product12").hide();
$("#Product13").hide();
}
function showProduct(productId)
{
var product = "#Product" + productId;
$(product).show();
}
</script>

Related

Range slider next and prev values always going to next value when moving

I write a code for range slider with some specific range values
[1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000,13000,14000,15000,16000,17000,18000,19000,20000,21000,22000,23000,24000, 25000,30000,35000,40000,45000, 50000, 60000,70000, 80000, 90000, 100000]
but when I move the slider curser in-between 4000-5000 for example 4320 it always goes to 5000 in-fact I want to move it on 4000 when moving slider to backword.
Also background-color behaving weirdly due to slider jumps.
this is how my JS looks like:
const slider = document.getElementById("myinput")
const min = parseInt(slider.min)
const max = parseInt(slider.max)
const value = parseInt(slider.value)
slider.style.background = `linear-gradient(to right, #0080FF 0%, #0080FF ${(value-min)/(max-min)*100}%, #596680 ${(value-min)/(max-min)*100}%, #596680 100%)`
slider.oninput = function() {
this.style.background = `linear-gradient(to right, #0080FF 0%, #0080FF ${(this.value-this.min)/(this.max-this.min)*100}%, #596680 ${(this.value-this.min)/(this.max-this.min)*100}%, #596680 100%)`
};
//
var arr = [1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000,13000,14000,15000,16000,17000,18000,19000,20000,21000,22000,23000,24000, 25000,30000,35000,40000,45000, 50000, 60000,70000, 80000, 90000, 100000];
var ele = document.querySelector('.slider')
ele.setAttribute('step', arr[0]);
var i = 0;
function a() {
ele.removeAttribute('step')
var value = ele.value
for (i = 0; i < arr.length; i++) {
if (arr[i] > value) {
ele.value = arr[i]
break;
}
}
document.querySelector('span').innerHTML = ele.value
}
//
// Add a change event listener to the range slider
slider.addEventListener('change', function() {
// Get the value of the range slider
var value = parseInt(this.value);
var container = document.querySelector('#rangeValue');
let cost;
if (value === 1000) {
cost = 0.0350;
} else if (value > 1000 && value <= 2000) {
cost = 0.0340;
} else if (value > 2000 && value <= 3000) {
cost = 0.0329;
} else if (value > 3000 && value <= 4000) {
cost = 0.0319;
} else if (value > 4000 && value <= 5000) {
cost = 0.031;
} else if (value > 5000 && value <= 6000) {
cost = 0.0301;
} else if (value > 6000 && value <= 7000) {
cost = 0.0292;
} else if (value > 7000 && value <= 8000) {
cost = 0.0283;
} else if (value > 8000 && value <= 9000) {
cost = 0.0274;
} else if (value > 9000 && value <= 10000) {
cost = 0.0266;
} else if (value > 10000 && value <= 11000) {
cost = 0.0258;
} else if (value > 11000 && value <= 12000) {
cost = 0.025;
} else if (value > 12000 && value <= 13000) {
cost = 0.0243;
} else if (value > 13000 && value <= 14000) {
cost = 0.0236;
} else if (value > 14000 && value <= 15000) {
cost = 0.0228;
} else if (value > 15000 && value <= 16000) {
cost = 0.0222;
} else if (value > 16000 && value <= 17000) {
cost = 0.0215;
} else if (value > 17000 && value <= 18000) {
cost = 0.0209;
} else if (value > 18000 && value <= 19000) {
cost = 0.0202;
} else if (value > 19000 && value <= 20000) {
cost = 0.0196;
} else if (value > 20000 && value <= 21000) {
cost = 0.019;
} else if (value > 21000 && value <= 22000) {
cost = 0.0185;
} else if (value > 22000 && value <= 23000) {
cost = 0.0179;
} else if (value > 23000 && value <= 24000) {
cost = 0.0174;
} else if (value > 24000 && value <= 25000) {
cost = 0.0168;
} else if (value > 25000 && value <= 30000) {
cost = 0.0163;
} else if (value > 30000 && value <= 35000) {
cost = 0.0159;
} else if (value > 35000 && value <= 40000) {
cost = 0.0154;
} else if (value > 40000 && value <= 45000) {
cost = 0.0149;
} else if (value > 45000 && value <= 50000) { //check
cost = 0.0145;
} else if (value > 50000 && value <= 60000) {
cost = 0.014;
} else if (value > 60000 && value <= 70000) {
cost = 0.0136;
} else if (value > 70000 && value <= 80000) {
cost = 0.0132;
} else if (value > 80000 && value <= 90000) {
cost = 0.0128;
} else if (value > 90000 && value <= 100000) {
cost = 0.0124;
}
var totval = value * cost;
totval = totval.toFixed(2);
container.innerHTML = totval;
// Print the value to the console
// console.log(value);
});
const
range = document.getElementById('myinput'),
rangeV = document.getElementById('rangeV'),
setValue = () => {
const
newValue = Number((range.value - range.min) * 100 / (range.max - range.min)),
newPosition = 10 - (newValue * 0.2);
rangeV.innerHTML = `<span>${range.value}</span>`;
rangeV.style.left = `calc(${newValue}% + (${newPosition}px))`;
};
document.addEventListener("DOMContentLoaded", setValue);
range.addEventListener('input', setValue);
JSFIDDLE of all the code
I found the solution to my problem.
This code will set the value of the slider to the nearest value in the array when the user moves the slider. It will also maintain the slider value when moving backward.
It also removes the unnecessary variable assignments and the for loop that was causing the background color to jump.
const slider = document.getElementById("myinput");
slider.oninput = function() {
this.style.background = `linear-gradient(to right, #0080FF 0%, #0080FF ${(this.value-this.min)/(this.max-this.min)*100}%, #596680 ${(this.value-this.min)/(this.max-this.min)*100}%, #596680 100%)`;
};
// Add a change event listener to the range slider
slider.addEventListener('change', function() {
// Get the value of the range slider
var value = parseInt(this.value);
var container = document.querySelector('#rangeValue');
// Set the value of the slider to the nearest value in the array
var arr = [1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000,13000,14000,15000,16000,17000,18000,19000,20000,21000,22000,23000,24000, 25000,30000,35000,40000,45000, 50000, 60000,70000, 80000, 90000, 100000];
var nearest = arr.reduce(function (prev, curr) {
return (Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);
});
if (value < nearest) {
nearest = arr[arr.indexOf(nearest) - 1];
}
this.value = nearest;
// display the value on the slider
document.querySelector('span').innerHTML = this.value;
});

When I use a validation script in a form field, the value ends up being empty when I submit

I started studying Javascript about two weeks ago and I'm already trying to do some stuff for my company's website.
We have a wordpress elementor website, in which I created a new registration form, using javascript and Jquery to validate some specific fields, like CPF(like a SS number for brazilians), zip code and password.
All of these validation scripts are working fine, but just one of them (CPF), when I submit the form it sends without any value in this specific field.
Hope you guys can help me.
I used the following script to validate data of this field:
<input type="text" class="elementor-field elementor-size-lg elementor-field-textual" name="form-fields[field_cpf]" id="field_cpf" placeholder="Digite apenas números." maxlength="11" minlength="11" onblur="alertarFuncao()" required="required" aria-required="true">
<script>
//validation script
function verificaCPF(strCpf) {
var soma;
var resto;
soma = 0;
if (strCpf == "00000000000" ||
strCpf == "11111111111" ||
strCpf == "22222222222" ||
strCpf == "33333333333" ||
strCpf == "44444444444" ||
strCpf == "55555555555" ||
strCpf == "66666666666" ||
strCpf == "77777777777" ||
strCpf == "88888888888" ||
strCpf == "99999999999") {
return false;
}
for (i = 1; i <= 9; i++) {
soma = soma + parseInt(strCpf.substring(i - 1, i)) * (11 - i);
}
resto = soma % 11;
if (resto == 10 || resto == 11 || resto < 2) {
resto = 0;
} else {
resto = 11 - resto;
}
if (resto != parseInt(strCpf.substring(9, 10))) {
return false;
}
soma = 0;
for (i = 1; i <= 10; i++) {
soma = soma + parseInt(strCpf.substring(i - 1, i)) * (12 - i);
}
resto = soma % 11;
if (resto == 10 || resto == 11 || resto < 2) {
resto = 0;
} else {
resto = 11 - resto;
}
if (resto != parseInt(strCpf.substring(10, 11))) {
return false;
}
return true;
}
//function if the field validation script returns false
function campoInvalido(fieldId) {
fieldId.style.borderColor = "red"
}
//function if the field validation script returns true
function campoValido(fieldId) {
fieldId.style.borderColor = "green"
}
//function that runs when the user clicks/taps out off the field
function alertarFuncao() {
var strCpf = document.getElementById('field_cpf').value;
verificaCPF(strCpf);
if (!verificaCPF(strCpf)) {
campoInvalido(document.getElementById('field_cpf'))
alert('Por favor, insira um CPF válido.');
} else {
campoValido(document.getElementById('field_cpf'));
return document.getElementById('field_cpf').value = strCpf
}
}
</script>```
I tested your code snipet on my own web server, and once I found an input which passes your checks it seems to work.
I see however that you didn't include a element in your snippet. The input must be a child of one of these elements in order to send data. If you have a closing tag directly above this input field you should probably move it under.
I solved the problem turning the HTML custom field of elementor form into a regular text field, and did some modifications on the script, inserting an event listener to it. As I understood this is an Elementor form "problem", it doesn't recognize values in custom HTML fieds when submitting.
Here's the modified code:
var soma;
var resto;
soma = 0;
if (strCpf == "00000000000" ||
strCpf == "11111111111" ||
strCpf == "22222222222" ||
strCpf == "33333333333" ||
strCpf == "44444444444" ||
strCpf == "55555555555" ||
strCpf == "66666666666" ||
strCpf == "77777777777" ||
strCpf == "88888888888" ||
strCpf == "99999999999") {
return false;
}
for (i = 1; i <= 9; i++) {
soma = soma + parseInt(strCpf.substring(i - 1, i)) * (11 - i);
}
resto = soma % 11;
if (resto == 10 || resto == 11 || resto < 2) {
resto = 0;
} else {
resto = 11 - resto;
}
if (resto != parseInt(strCpf.substring(9, 10))) {
return false;
}
soma = 0;
for (i = 1; i <= 10; i++) {
soma = soma + parseInt(strCpf.substring(i - 1, i)) * (12 - i);
}
resto = soma % 11;
if (resto == 10 || resto == 11 || resto < 2) {
resto = 0;
} else {
resto = 11 - resto;
}
if (resto != parseInt(strCpf.substring(10, 11))) {
return false;
}
return true;
}
function campoInvalido(fieldId) {
fieldId.style.borderColor = "red"
}
function campoValido(fieldId) {
fieldId.style.borderColor = "green"
}
function alertarFuncao() {
var strCpf = document.getElementById('form-field-field_cpf').value;
verificaCPF(strCpf);
if (!verificaCPF(strCpf)) {
campoInvalido(document.getElementById('form-field-field_cpf'))
alert('Por favor, insira um CPF válido.');
} else {
campoValido(document.getElementById('form-field-field_cpf'));
return document.getElementById('form-field-field_cpf').value = strCpf
}
}
document.getElementById('form-field-field_cpf').addEventListener("blur", alertarFuncao);```

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.

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;
}

Is it possible to replace two opposite and different functions with a single one?

I want to optimise and reduce my code to increase performance and correct-ability of it. With those two different functions below I can successfuly move a Google Map Marker on a map forward and backward using a pathIndex, calcuted on an array of GPS coordinates [I didn't include this section of code since I think it's not releated to this question but I can and will post it if needed].
This is my code:
1st function:
function animate() {
if (pathIndex < coord.length && mapAnimationStatus != PLAY_PAUSED) {
googleMapsMarker.setPosition(coord[pathIndex]);
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
timerHandler = setTimeout("animate(" + pathIndex + ")", 1000);
}
}
2nd function:
function animateRewind() {
if (pathIndex >= 0 && mapAnimationStatus != PLAY_PAUSED) {
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
timerHandler = setTimeout("animateRewind(" + pathIndex + ")", 1000);
}
}
As you can see those two functions shares a lot of portions of code and it think that they can be replaced with a single one for this reason but I can't figure out how to do this.
So, is it possible to create a single function to manage those two different animations?
I hope I didnt miss something...
function animate(pathIndex, dir) {
var animateDir = (pathIndex < coord.length
&& mapAnimationStatus != PLAY_PAUSED && dir == 'f')
? dir
: (pathIndex >= 0
&& mapAnimationStatus != PLAY_PAUSED && dir == 'r')
? dir : "error";
if (animateDir === "r") { googleMap.panTo(coord[pathIndex]); }
if (animateDir !== 'error') { googleMapsMarker.setPosition(coord[pathIndex]); }
if (animateDir === "f") {
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
}
if (animateDir !== 'error') {
if (pathIndex == coord.length || pathIndex == 0) {
pause();
pathIndex = animateDir === "f" ? 0 : pathIndex;
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex = animateDir === "f" ? pathIndex - 1 : pathIndex;
timerHandler = setTimeout("animate(" + pathIndex + "," + animateDir + ")", 1000);
}
}
You can try this :
function ConcatenateFunctions() {
if(mapAnimationStatus != PLAY_PAUSED){
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex < coord.length) {
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
}else if (pathIndex >= 0) {
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
}
timerHandler = setTimeout("ConcatenateFunctions(" + pathIndex + ")", 1000);
}
}
Hope it will help !

Categories