Shortening if, else if, else if ... else using loops - javascript

I have the following lines of code:
$(function(){
$("div").scroll(function() {
function hpos(id) {
var pos = $("#" + id).position();
return pos.top;
}
function final(id) {
$("#header").html($("#" + id).html()),
$("h1").css("visibility","visible"),
$("#" + id).css("visibility","hidden");
}
if (hpos(5) < 0) {
final(5);
}
else if (hpos(4) < 0) {
final(4);
}
else if (hpos(3) < 0) {
final(3);
}
else if (hpos(2) < 0) {
final(2);
}
else {
final(1);
}
});
});
Shouldn't I be able to shorten it by using a loop instead of the else if statements? I can't find a way to make the loops work with my position().

for (var i = 5; i > 0; i--){
if (hpos(i) < 0) {
final(i);
break;
}
}
would something like this work? Not tested by the way

This should be shorter:
$.each([5,4,3,2], function(i,v) {
if( hpos(v) < 0 ) {
final(v);
return false;
} else if( v === 2 ) {
final(1);
}
});

An easier way to do lots of else if statements is to use the case method.

In case you need a while version:
:)
var elemId = 5;
while (elemId > 1) {
if (hpos(elemId) < 0) {
break;
}
elemId--;
}
final(elemId);

Related

Jquery if value <= something dont working

Help me please to understand why not working that part of code.
I'm trying to style a block depending on a variable, but that part doesn't work.
var starsrating = 3;
function markstars() {
if (jQuery(starsrating).val() >= 1) {
jQuery("div.rating-star1").addClass("rating-star-active");
console.log("1");
}
if (jQuery(starsrating).val() >= 2) {
jQuery("div.rating-star1, div.rating-star2").addClass("rating-star-active");
console.log("2");
}
if (jQuery(starsrating).val() >= 3) {
jQuery("div.rating-star1, div.rating-star2, div.rating-star3").addClass("rating-star-active");
console.log("3");
}
if (jQuery(starsrating).val() >= 4) {
jQuery("div.rating-star1, div.rating-star2, div.rating-star3, div.rating-star4").addClass("rating-star-active");
console.log("4");
}
if (jQuery(starsrating).val() >= 5) {
jQuery("div.rating-star1, div.rating-star2, div.rating-star3, div.rating-star4, div.rating-star5").addClass("rating-star-active");
console.log("5");
}
console.log("end of func");
}
markstars();
starsrating is a plain number; you can't call jQuery on it.
A further simplification is to loop over all numbers 1..5 and set the states of the divs programmatically:
function markstars(starsrating) {
for (var i = 1; i <= 5; i++) {
jQuery("div.rating-star" + i).toggleClass("rating-star-active", starsrating >= i);
}
}
markstars(3);

Need to check and alert duplicate value in an array

I can see the array in console but can not check them if there are same values in it.
$('.tab2field').each(function () {
PackageName.push($('.span2', this).val() );
PackageCount.push($('.ex > :selected', this).text())
});
This is what i am trying to do.
for (var i = 0; i <PackageName.length; i++) {
if (PackageName[i] != current) {
if (cnt > 0) {
}
current = PackageName;
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 1) {
alert(' Check multiple inputs');
}
You can do checking before pushing:
$('.tab2field').each(function () {
var name = $('.span2', this).val();
if (PackageName.indexOf(name) === -1) {
PackageName.push(name);
PackageCount.push($('.ex > :selected', this).text())
} else {
console.warn('Package ' + name + ' is already included');
}
});
But I am not sure whether this is what you wanted to achieve becuase your question is a bit unclear

Brainfuck interpreter loop trouble

I am currently making a brainfuck and have encountered a problem with loops.
I followed some advice from this but I can't seem to get it working.
Here is my code so far:
<html>
<body>
<font face="consolas">
<script>
var brPos = 0;
var k = 0;
var loop = [];
var printtape = "";
var out = "";
var i = 0;
var pointer = 0;
var tape = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var source = prompt("Code").split("");
while (i<source.length+1){
if (source[i] == "<"){
pointer--;
} else if (source[i] == ">"){
pointer++;
} else if (source[i] == "+"){
tape[pointer]++;
} else if (source[i] == "-"){
tape[pointer]--;
} else if (source[i] == ","){
tape[pointer] = prompt("Input").charCodeAt(0);
} else if (source[i] == "."){
out += String.fromCharCode(tape[pointer]);
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
i++;
for (j=0;j<tape.length;j++) {
if (tape[j] > 255) {
tape[j] = 0;
} else if (tape[j] < 0) {
tape[j] = 255;
}
}
console.log(tape);
console.log(loop);
}
printtape = "";
printtape += "|";
for (i=0;i<tape.length;i++) {
if (tape[i]<10) {
printtape += "00"+tape[i]+"|";
}
if (tape[i]>=10&&tape[i]<100) {
printtape += "0"+tape[i]+"|";
}
if (tape[i]>=100) {
printtape += tape[i]+"|";
}
}
printtape += "<br>";
printtape += "  ";
for (i=0;i<pointer;i++) {
printtape += "    ";
}
printtape += "^";
document.write(printtape);
alert(out);
</script>
</font>
</body>
</html>
This is the offending code (I think):
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
When I run the code (in IE) with a brainf*ck loop in it, it doesnt end the while loop and eventually crashes and I don't know why.
P.S. I know someone in the comments is going to say that the <font> tag is invalid HTML, and I should use CSS, but it works, it's quicker than CSS and I really don't care.
There's nothing I know about Brainfuck parsing, but the code logic fails and you get infinite loop because brPos is a constant inside the loop. You make the same comparations and get to the k++ line over and over again. brPos has to be changed if you ever wanna get out of there.

JavaScript iterate through items backwards

I am iterating through some photos using this code:
if (this.lightboxIndex < this.photos.length - 1) {
this.lightboxIndex++;
} else {
this.lightboxIndex = 0;
}
this.lightboxSrc = this.photos[this.lightboxIndex].src;
},
How can i iterate backwards through the same photos? Is this along the lines of what I need to do?
if(this.lightboxIndex < this.photos.length - 1){
this.lightboxIndex--;
} else {
this.lightboxIndex = 0;
}
this.lightboxSrc = this.photos[this.lightboxIndex].src;
},
When you're iterating down, you need to check for reaching 0, not the highest index, and then go back to the highest index.
if (this.lightboxIndex == 0) {
this.lightboxIndex = this.photos.length - 1;
} else {
this.lightboxIndex--;
}
Your if test will always succeed, so it will just keep decrementing the index, going into negative numbers.
if(this.lightboxIndex > 0) {
this.lightboxIndex--;
} else {
this.lightboxIndex = this.photos.length - 1;
}
this.lightboxSrc = this.photos[this.lightboxIndex].src;
Why not use a decrementing for loop?
for (this.lightboxIndex = (this.photos.length - 1); this.lightboxIndex >= 0; this.lightboxIndex--) {
this.lightboxSrc = this.photos[this.lightboxIndex].src;
}
let think backward will go from last to first ,so if it is first index,assign to last index else decrease to first index !
forward will go from first to last ,so if it is last index , assign back to first index else increase to last index !
this.lightboxIndex = 0;
this.photos = ['a','b','c'];
function forward(){
if (this.lightboxIndex == this.photos.length -1) {
this.lightboxIndex = 0;
} else {
this.lightboxIndex++;
}
this.lightboxSrc = this.photos[this.lightboxIndex];
console.log(this.lightboxSrc);
}
function backward () {
if(this.lightboxIndex == 0) {
this.lightboxIndex = this.photos.length -1;
}
else {
this.lightboxIndex--;
}
this.lightboxSrc = this.photos[this.lightboxIndex];
console.log(this.lightboxSrc);
}
forward();
forward();
forward();
backward();
backward();
backward();

stop for execution javascript?

Well, I'm trying to get him to make some fields, if any of them is equal, it's the message and, though my message is giving non-stop, direct, how can I make it stop giving a lot of alert?
function sendAll(){
for (i = 1;i <=10;i ++) {
for (o = 1;o <=10;o ++) {
if(document.getElementById("table" + i).value==document.getElementById("table" + o).value){
alert("Some field is equal, check again.");
break;
return false;
}
}
}
}
You don't need break statement, just remove it. return statement will do the rest
use
function sendAll() {
for (i = 1; i <= 10; i++) {
for (o = 1; o <= 10; o++) {
if (document.getElementById("table" + i).value == document.getElementById("table" + o).value) {
alert("Some field is equal, check again.");
//break;
return false;
}
}
}
//If you are using for validation purpose return true
// as default
return true;
}
Your break simply stops the inner-most loop, but allows the outer loop to continue. To break out of the function entirely, just use a return:
function sendAll(){
for (i = 1;i <=10;i ++) {
for (o = 1;o <=10;o ++) {
if(document.getElementById("table" + i).value==document.getElementById("table" + o).value){
alert("Some field is equal, check again.");
return false;
}
}
}
return true; // suggested by Mike W
}
Try something like this
function sendAll(){
var bEqual = false;
for (i = 1;i <=10;i ++) {
for (o = 1;o <=10;o ++) {
if(document.getElementById("table" + i).value==document.getElementById("table" + o).value){
bEqual = true;
}
}
}
if (bEqual) {
alert("Some field is equal, check again.");
}
return bEqual;
}
Perhaps you could do:
function sendAll(){
if (!fieldsOk()) {
alert('some message');
}
}
function fieldsOk() {
for (i = 1;i <=10;i ++) {
for (o = 1;o <=10;o ++) {
if(document.getElementById("table" + i).value==document.getElementById("table" + o).value){
return false;
}
}
}
return true;
}

Categories

Resources