Google Script - Consolidated operator syntax not working in IF statement - javascript

Conext
I would like my onEdit(e) function below to add or remove rows from a spreadsheet based on the new and old values of a cell. This requires the OR (||) operator in my IF statement to check the values. Below is my first attempt which sort of worked but led to some odd behavior such as rows appearing then disappearing (the second IF statement) after a single edit, two rows appearing whenever I hit the "delete" key, etc:
function onEdit(e) {
var range = e.range;
var newValue = e.value;
var oldValue = e.oldValue;
var targetRow = range.getRow();
//insert 2 rows if edited cell value = "a" or "b"
if (newValue === "a" || "b") {
sheet.insertRowsAfter(targetRow, 2);
}
//delete 2 rows if former cell value was "a" or "b"
if (oldValue === "a" || "b") {
sheet.deleteRows(targetRow + 1, 2);
}
}
Applications Currently Used
Google Sheets
Google Apps Script
What I've Tried So Far
When I changed my IF statements to restate the variable after each OR operator, the desired result was produced cleanly:
if (newValue === "a" || newValue === "b") {
sheet.insertRowsAfter(targetRow, 2);
}
if (oldValue === "a" || oldValue === "b") {
sheet.deleteRows(targetRow + 1, 2);
}
Question
Is there a consolidated form of writing these statements that will continue to produce the desired result? As I continue writing this function, these IF statements are likely to become more complex and the same variable will need to be checked using OR and AND operators. It would be much easier to only state the variable name once for each operator.
To recap:
I would like to be able to write the consolidated format of the code as shown in the first code snippet:
if (newValue === "a" || "b") { //etc...
However, it only works properly when written in the longer version:
if (newValue === "a" || newValue == "b") { //etc...
Thank you!

You could use the switch statement to consolidate.
switch (newValue) {
case "a":
case "b":
sheet.insertRowsAfter(targetRow, 2);
break;
default:
}
You could add more cases there to "OR" the overall condition if required.

Related

Appropriate way to check if 4 strings are duplicated in JS [duplicate]

Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:
if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
yahtzeeQualify == true;
}
and this:
if (die1 == die2 == die3 == die4 == die5) {
yahtzeeQualify == true;
}
Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:
var dieArray = [die1, die2, die3, die4, die5];
It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...
Are either of these valid?
They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&) not a bitwise AND.
The second one is just wrong. You run into type coercion issues and end up comparing die1 to either true or false.
It would be cool to learn a way to do this via the array
You can use Array#every and compare whether each element is equal to the first one:
if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))
Solution with the Array.reduce:
var values = [die1, die2, die3, die4, die5];
var yahtzeeQualify = values.reduce(function(memo, element) {
return element === values[0];
});
The 1st one is what you want, but it's messed up. You want && not &
The 2nd one is logically wrong.
To do it with an array
yahtzeeQualify = dieArray.every(function(n){ return n === dieArray[0] })

HeadFirst JS: questions in an example of code

The purpose of the function is to validate input. The input should consist of two characters: the first one A-G; the second one: 0-6; e.g A0; B2. The example is taken from the book.
I want to understand is there a point in lines such as: "guess===null (Can a string be equal to null?)" ; " column < 0 " row >= model.boardsize;
Note that model.boardsize is a specified number. In this case, it is 7.
function parseGuess(guess) {
var alphabet = ["A" , "B" , "C", "D", "E", "F", "G"];
if (guess===null || guess.length !== 2) {
alert("Oops, please enter a letter and a number on the board.");
} else {
var firstChar = guess.charAt(0);
var row = alphabet.indexOf(firstChar);
var column = guess.charAt(1);
if (isNaN(row) || isNaN(column)) {
alert("Oops, that isn't on the board.");
} else if (row < 0 || row >= model.boardSize ||
column < 0 || column >= model.boardSize) {
alert("Oops, that's off the board!");
} else {
return row + column;
}
}
return null;
};
I haven't read the book and it's not clear how this function gets called, but I would say that's a pretty poor check for determining if guess has a good, expected value. The typical reason why one would check for null first is because if guess is null, then guess.length will throw a TypeError because null does not have a length property. Since it is the first check in the OR condition, it short-circuits the second half and shows the alert() right away when guess is null.
However, an error would also be thrown if guess was undefined (a common case when an argument isn't passed in the function call) or a boolean. Additionally, objects, arrays, and other data structures also have a length property, which means they could pass the first if condition test but then methods like indexOf and charAt would throw errors. You would probably want to change it to something like:
if (typeof guess !== 'string' && guess.length !== 2) {
As for the board size, yes you want to check if the column is less than 0 or greater than the size, otherwise you will pick something out-of-bounds and your program will throw an error.

replacing variables of an array in a loop

I'm trying to make some sort of cryptographer, and I need to replace for ex. every "a" with "b" when the user asks for it.
if (DoYouWannaCrypt == 1) {
binput.forEach(function(v, i) {
if(v === "a") {
input[i] = "$"
}
})
};
This works fine, however I want to add another condition that this should only be done for all 5th values of another array.
if (Val is 5th) {
if (DoYouWannaCrypt == 1){
binput.forEach(function(v, i) {
if(v === "a") {
input[i] = "$"
}
})
}
};
I think you can see where I'm stuck at. I need it to work for all 5th values not just the first one.
Thats what map is for:
var crypted=binput.map((l,i)=>(i+1)%5?l:({"a":"$"}[l]||l));
http://jsbin.com/zepewituro/edit?console
Check if index (starting from 0, thats why +1 ) modulo 5 is not 0,then take the letter l, if its 0 ( then we are at the 5*n th position), then we try to replace our letter with another one, if it isnt possible fallback to the letter (||l).
Since your code appears irrelevant to your problem, let me store it safely in a function first:
function something(binput, input, DoYouWannaCrypt) {
if (DoYouWannaCrypt == 1)
binput.forEach(function(v, i) {if (v === "a") input[i] = "$"});
}
If you want to do this operation only for the first element of anotherArray:
for (let Val in anotherArray)
if (!Val) something(binput, input, DoYouWannaCrypt);
If you want to do it for every element of anotherArray:
for (let Val in anotherArray)
something(binput, input, DoYouWannaCrypt);
If you want to do it for every fifth element of anotherArray:
for (let Val in anotherArray)
if (!(Val%5)) something(binput, input, DoYouWannaCrypt);

Can you compare multiple variables to see if they all equal the same value in JS?

Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:
if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
yahtzeeQualify == true;
}
and this:
if (die1 == die2 == die3 == die4 == die5) {
yahtzeeQualify == true;
}
Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:
var dieArray = [die1, die2, die3, die4, die5];
It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...
Are either of these valid?
They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&) not a bitwise AND.
The second one is just wrong. You run into type coercion issues and end up comparing die1 to either true or false.
It would be cool to learn a way to do this via the array
You can use Array#every and compare whether each element is equal to the first one:
if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))
Solution with the Array.reduce:
var values = [die1, die2, die3, die4, die5];
var yahtzeeQualify = values.reduce(function(memo, element) {
return element === values[0];
});
The 1st one is what you want, but it's messed up. You want && not &
The 2nd one is logically wrong.
To do it with an array
yahtzeeQualify = dieArray.every(function(n){ return n === dieArray[0] })

checking values before submitting form

Before I submit a form I want to check the values in the input.
Here I'm checking if a value is NOt equal to .5 or 1. or not a empty string.
form.onsubmit = function(e) {
var ftimes = document.getElementsByClassName("add_timebox");
var fflag = 0;
for(i=0;i< ftimes.length;i++) {
var value1 = ftimes[i].value;
console.log(value1);
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
}
}
if(fflag==1) {
alert('enter again' );
return false;
}
I have made many changes to the IF statement to try to get it correct.
But it is still going in the loop even when I know if shouldn't.
For example when i submit the form and i have one input value equal .22
then it should only give me 1 'inside' but in keeps repeating:
inside
.22
(empty string)
inside
....
You do not show how you are implementing your IsStringEmpty method, but if you are using something like this, then any number is also a non-empty string, so your if statement will always run.
function IsStringEmpty(str) {
return (!str || 0 === str.length);
}
So you need to change your ORs with ANDs, or it will never check the number conditions.
You can check if the value is not an empty string and is different from 0.5 and 1. Then your condition should be like this.
if (!IsStringEmpty(value1) && value1 !== 0.5 && value1 !== 1)
But, you are getting the value from a form, so it will be a string. Therefore, you are comparing strings and you need this.
if (!IsStringEmpty(value1) && value1 !== ".5" && value1 !== "1")
Although you will probably want to compare floats, in which case you need this.
if (!IsStringEmpty(value1) && parseFloat(value1) !== .5 && parseFloat(value1) !== 1))
So basically, when you enter 1, .5 or and empty string in all of the form fields, you skip the inside block. But if you have any other value in any of the fields, then the flag will be set to 1. If that is not what you meant, please update your question to be more specific.
Please check Plunker here.
Hope this helps.
you have to add a break; statment in your if condition once the if condition is satisfied.
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
break;
}

Categories

Resources