How do I jump from one loop to another? - javascript

So I'm trying to make a loop that does something and then when it is finished set a var to false then move to the next loop (or otherwise exit and end the loop). Code:
var loop = true;
while (loop = true)
{
console.log("whatevers");
loop = false;
}
while (loop = false)
{
console.log("meh");
//continue endProgram;
}
So what am I doing wrong here?

= is just assignment, where == or === is for comparisons. Assignment of a variable is evaluated as the expression after the assignment (see #Oka comment). For example: (loop = true => true while loop = false => false) Use == or === instead:
var loop = true;
while (loop == true)
{
console.log("whatevers");
loop = false;
}
while (loop == false)
{
console.log("meh");
//continue endProgram;
}

Try this way
-------------------------------------------------------------------
var loop = true;
while (loop)
{
console.log("whatevers");
loop = false;
}
while (!loop)
{
console.log("meh");
//continue endProgram;
}

while(loop) is the same with while(loop == true )..but loop = true means that you set variable loop equal to true.So try this:
var loop = true;
while (loop)
{
console.log("whatevers");
loop = false;
}
while (!loop)
{
console.log("meh");
}

Related

Reset loop with condition

I'm coding project with codewars and have a trouble. This function has to check if parentheses in string are valid. My problem is when i assign i = 0 in function valid pair it's doesnt work . I tried assign it below if statement and then my loop is infinite. My idea is valid pairs and then start over and over while parens.lenght will be <= 2 then i know that there left a pair and i can nothing to do with it. Could you help me?
// "()" => true
// ")(()))" => false
// "(" => false
// "(())((()())())" => true
const validPair = (parens) => {
console.log(parens);
for (let i = 0; i < parens.length; i++) {
if (parens[i] == '(' && parens[i + 1] == ')') {
parens.splice(i, 2);
i = 0;
console.log(parens.length);
}
if (parens.length <= 2) {
console.log(parens);
}
}
console.log(parens);
};
function validParentheses(parens) {
let validLength = 0;
parens = parens.split('');
parens.forEach((el) => {
if (el == '(') {
validLength++;
} else {
validLength--;
}
});
if (validLength != 0) {
return false;
} else {
validPair(parens);
}
}
console.log(validParentheses('(()))(()'));
I will be updating this code but i stuck in this moment and dont know what to do.
You've overcomplicated things
Simply counting is enough
// "()" => true
// ")(()))" => false
// "(" => false
// "(())((()())())" => true
function validParentheses(parens) {
let lefts = 0
for (const par of parens) {
if (par === '(') {
lefts += 1
} else {
lefts -= 1
}
if (lefts < 0) return false
}
if (lefts !== 0) return false
return true
}
console.log(validParentheses('()'));
console.log(validParentheses('(()))(()'));
console.log(validParentheses('('));
console.log(validParentheses('(())((()())())'));
Approach:
The idea is to use stack. so when you get ( you need to push it to stack and when you get ) you need to pop it. And at the end just need to check stack is still empty or not. if stack is empty that means parentheses are valid.
Edge case:
When there's no element in the stack and you have ) that means there's no ( bracket to match with it. so it returns false.
const validParentheses = (str) => {
const stack = [];
for (let parentheses of str) {
if (parentheses == '(') stack.push(parentheses);
else {
if (!stack.length) return false;
stack.pop();
}
}
return !stack.length;
}
console.log(validParentheses("()"));
console.log(validParentheses(")(()))"));
console.log(validParentheses("("));
console.log(validParentheses("(())((()())())"));

Why doesn't this function exit after the first iteration?

I do understand how the following function works in general. BUT why doesn't it exit after the first iteration (when there is a palindrome)? It checks the first character against the last in the if statement, which is true, what should (in my logic) execute the return statement... Thank you for any help explaining this! :)
function palindrome(str) {
var lowerCaseStr = str.toLowerCase();
for (var i = 0; i < lowerCaseStr.length; i++)
debugger;
if (lowerCaseStr[i] === lowerCaseStr[lowerCaseStr.length - i - 1]){
return true;
}
return false;
}
It doesn't exit after the first iteration but after lowerCaseStr.length iterations because your code is equivalent to the code below
function palindrome(str) {
var lowerCaseStr = str.toLowerCase();
for (var i = 0; i < lowerCaseStr.length; i++){
debugger;
}
if (lowerCaseStr[lowerCaseStr.length] === lowerCaseStr[-1]){
return true;
}
return false;
}
that is, it iterates lowerCaseStr.length; times but the only thing it does for each iterates is call debugger after that it tests to elements in the array that doesn't exists. (Both indices are out of bounds). That results in a comparison of two times undefined undefined === undefined which is always true.
As a side node if you return either true or false depending on a boolean expression then consider using one return statement instead:
return (lowerCaseStr[i] === lowerCaseStr[lowerCaseStr.length - i - 1]);
You need to switch the logic, check for inequality and return false. If you reach the end, return true.
function palindrome(str) {
var lowerCaseStr = str.toLowerCase();
for (var i = 0; i < lowerCaseStr.length; i++) {
debugger;
if (lowerCaseStr[i] !== lowerCaseStr[lowerCaseStr.length - i - 1]) {
return false;
}
}
return true;
}

javascript for loop is not incrementing

I am trying to using a for loop for trying to validate the input of the user and this is the code i got.
function Valid() {
objfieldid = ["userMail", "userCont"]
objboxid = ["cancelMail", "cancelCont"]
return objfieldid.every(callnonvalid)
}
function callnonvalid(id) {
var valid = false
var objlength = objfieldid.length
objlength--;
for (var i = objlength; i >= 0; i--){
var cobj = document.getElementById(objboxid[i]).checked;
if (document.getElementById(id).value != "" ){
var obj = document.getElementById(id).value;
} else if (cobj == true) {
alert(i); //return 1, 1
return true
} else {
return false
}
}
}
As you can see, in the code, the for loop is running twice. but the i variable is left unchanged. Why would this happen?
btw, I did read different material about closure and i am sure there didnt got a closure problem
EDIT:guys please note that i did noticed the array is zero based, and i did minus the objlength by one.
Mistakes were found after checking the code carefully. The Mistake that I made was that I should not use the return for the out since that would stop the function from working, however that array.every Called the function twice which make the i not decreasing
I'm not sure why you're decrementing in your loop, because the performance gain would be infinitesimally small (it may even be slower, e.g. in Chrome/V8) and working in reverse order can get confusing further down the line, but that's your choice and I don't know enough about what you're doing to judge.
Either way, I don't think you'd want to decrement objlength before the loop begins as you are doing now. The whole point of a loop is to handle the incrementing/decrementing in the condition statement of the loop.
You would only decrement manually like that if you were going to move your if/else if/else statement into a closed over function and execute it recursively, decrementing the objlength from within the closure. Which would work, but it's unnecessarily complicated for what you're doing and you would gain nothing for rewriting the whole thing.
So, sticking with the looping approach, perhaps try either of these:
function Valid() {
objfieldid = ["userMail", "userCont"];
objboxid = ["cancelMail", "cancelCont"];
return objfieldid.every(callnonvalid);
}
function callnonvalid(id) {
var valid = false;
var objlength = objfieldid.length;
for(var i = 0; i < objlength; i++){
var cobj = document.getElementById(objboxid[i]).checked;
if (document.getElementById(id).value != "" ){
var obj = document.getElementById(id).value;
} else if (cobj == true) {
alert(i);
return true;
} else {
return false;
}
}
}
or, if you want to decrement, use while instead of for:
function Valid() {
objfieldid = ["userMail", "userCont"];
objboxid = ["cancelMail", "cancelCont"];
return objfieldid.every(callnonvalid);
}
function callnonvalid(id) {
var valid = false;
var i = objfieldid.length;
while(i--){
var cobj = document.getElementById(objboxid[i]).checked;
if (document.getElementById(id).value != "" ){
var obj = document.getElementById(id).value;
} else if (cobj == true) {
alert(i);
return true;
} else {
return false;
}
}
}
Because the array objboxid[] has only two elements, the first time through your loop objboxid[2] will be attempting to fetch an array index that is out-of-bounds.
You probably meant something like:
for (var i = objlength; i > 0; i--){
var cobj = document.getElementById(objboxid[i-1]).checked;
or perhaps
for (var i = objlength-1; i >= 0; i--){
var cobj = document.getElementById(objboxid[i]).checked;

Angular: How to break from outer loop from inner loop?

I tried using break Statement. but didnt worked out. I wanted to break out from outer loop as soon as some condition matches in inner loop.
angular.forEach(myfilejob, function(fieldMapO) {
var count = 0;
angular.forEach(myfilejob, function(fieldMapI) {
if(fieldMapO.key == fieldMapI.key){
$scope.dupKey = fieldMapI.key;
count ++;
}
});
if(count>1){
$scope.dups = true;
// tried break , but didnt work
}
else{
$scope.dups = false;
}
});
When you use forEach, there is no way to pause iteration - not even by using return. If you want a way to stop iteration in the middle of your loop, you must use an actual for or while loop (probably something like for..in or for..of or a traditional three-statement for(var i = 0; i < whatever; i++ loop if myfilejob is an array).
However, once you have done that, you can then label the loops to get the exact effect you're looking for:
outerDupLoop:
for (var outerIndex in myfilejob) {
var fieldMapO = myfilejob[outerIndex];
var count = 0;
innerDupLoop:
for (var innerIndex in myfilejob) {
var fieldMapI = myfilejob[innerIndex];
if(fieldMapO.key == fieldMapI.key){
$scope.dupKey = fieldMapI.key;
count ++;
}
});
if(count>1){
$scope.dups = true;
break outerDupLoop; // break from the outer loop
} else {
$scope.dups = false;
}
}
(Never mind that the break statement you were trying to add was in the outer loop anyway - removing the labels from this example would make this functionally equivalent. Did you mean to refactor the (count > 1) check so that it would work properly inside the inner loop?)
You can use return, which will essentially break out of the loop. If you want to do it within the inner loop, set a boolean to true, and check for it in the outer loop.
var dupsExist = false;
angular.forEach(myfilejob, function(fieldMapI) {
if(fieldMapO.key == fieldMapI.key){
$scope.dupKey = fieldMapI.key;
dupsExist = true;
return;
}
});
if (dupsExist){
return;
}
I suggest you define a bool when your inner condition is satisfied
angular.forEach(myfilejob, function(fieldMapO) {
var count = 0;
var conditionFlag = false;
angular.forEach(myfilejob, function(fieldMapI) {
if(fieldMapO.key == fieldMapI.key){
$scope.dupKey = fieldMapI.key;
count ++;
//condition is fulfilled so boolean is true now
conditionFlag = true
return false
}
});
if(count>1){
$scope.dups = true;
}
else{
$scope.dups = false;
}
//check if condition is satisfied then exit outer loop too
if(conditionFlag){
return false;
}
});
Hope it helps

javascript: unreachable code in for iterator

Ok, im feeling kinda stupid with this one.
I am trying to define a function that checks wether an item is already present inside the listbox items collection (could be any collection actually)
here it is:
<script type="text/javascript">
function canInsert(listbox, item)
{
if (item == null)
return true;
var itemCount = listbox.GetItemCount();
for (var i = 0; i < itemCount; i++)
{
var nitem = listbox.GetItem(i);
if (nitem.value === item.value)
return false;
return true;
}
}
</script>
using VS 2015 CE, it says i++ is unreachable code. HOW AND WHY ?
Like Igor said, when you return true at the end of your for loop, JS will exit the function immediately returning the value 'true'.
You can execute the for loop you currently have, and if your if statement condition is met, false will be returned and the function will be exited. After your for loop, if the condition is never met, true will be returned. Your code should look like the below:
<script type="text/javascript">
function canInsert(listbox, item)
{
if (item == null)
return true;
var itemCount = listbox.GetItemCount();
for (var i = 0; i < itemCount; i++)
{
var nitem = listbox.GetItem(i);
if (nitem.value === item.value)
return false;
}
return true;
}
</script>

Categories