What is the cause for this odd OR and ternary output [Javascript] - ternary

Hey so I am having an issue with an OR and ternary operation. I have this code here.
console.log(this.state.records)
Before: {
AllowCheck: "1"
Checked: "0"
}
const records = this.state.records.map((record) => {
return {
...record,
Checked: checked || record.AllowCheck === '0' ? '1' : '0',
}
});
console.log(records)
After: {
AllowCheck: "1"
Checked: "1"
}
When you look at the log before the ternary operation, you see that the object has a property called “AllowCheck”. You can see here that it evaluates as a 1 in the record. If you look at the function below, you’ll see a map operation that iterates over a list of records. The variable “checked” comes from a checkbox onChange operation that will evaluate as true in this situation. In the OR operation you can see that “checked” will be true, and the ternary on the right is where the “record.AllowCheck” will evaluated as a 1 from before. The ternary should result in a 0 since “record.AllowCheck” is 1. You’ll see in the after object that Checked is equal to 1. I don't know why it's not equal to two from the "checked" variables, and I really don't understand how it's equal to 1. Am I missing something? Have I been looking at this for too long? Any opinions or answers would be much appreciated, thank you.

The ternary should result in a 0 since “record.AllowCheck” is 1
Nope. The condition in this ternary operation is not what you think it is (record.AllowCheck === '0'). It's actually checked || record.AllowCheck === '0' and, since checked is truthy, it short-circuits on the first step, evaluates to true overall and that's how the ternary operator evaluates to '1'.
See the operator precedence table for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table

Related

Writing an if statement when the value can be NULL or a string

I have a value that can be NULL or a string. The second test fails because a is of length 0.
How do I write an if-statement that handles both cases?
Example:
a <- NULL
if (is.null(a) | a=="something else then null") {
print("test")
}
is.null(a) || a=="something else then null"
(similarly, use && instead of & in a situation like this)
Explanation: when you use |, all conditions are checked one by one and then the "or" assertion is applied. This means that if one of the conditions is invalid, then there is an error, like in your case.
When you use ||, the "or" assertion is checked after each condition check. In your case, is.null(a) is TRUE. This means that is.null(a) "or" any other condition will also be TRUE, so there's no need to check the other condition.
This is based on my understanding of how it works, it's not a definition coming from the docs. I hope it's clearer.
More info: What's the differences between & and &&, | and || in R?

Weird behavior with Maps(A nullable expression can't be used as a condition)

Map<String,bool> map= { "key1":true, "key2":false };
/*
* Flags following compilation error:
* A nullable expression can't be used as a condition.
* Try checking that the value isn't 'null' before using it as a condition.
*/
if(map["key1"]) {
//do sth
}
/*So I try checking value isn't null as specified in error
*Still flags same compilation error
*/
if(map!=null && map["key1"]) {
//do sth
}
//This works
if(map["key1"] == true) {
//do sth
}
}
Based on the following snippet, may I know why both the 1st and 2nd if blocks fail but not the 3rd?
You misunderstood the error message.
A nullable expression can't be used as a condition.
means that you can't do:
bool? condition;
if (condition) {
...
}
Map<K, V>'s operator[] returns a V?. It returns a nullable type as a way of indicating failure when the key isn't found, and you need to check that the returned value isn't null, not that map itself is not null. For example:
if (map["key"] ?? false) {
...
}
Your third approach (which checks == true) works because it will perform a null == true equality check if the lookup returns null. However, you should prefer using ?? false since it conveys the intent better, and equality checks against true or false are usually a code smell.
The [] operator on Map can return null which makes it nullable which is explained in details here: https://dart.dev/null-safety/understanding-null-safety#the-map-index-operator-is-nullable
So your first example is invalid since null is not a bool. So you cannot directly use the value from the [] operator for a Map.
Your second example is invalid for the same reason since map["key1"] is bool?.
Third example works since null == true is always false. So it is fully valid to make a comparison which involves something which can be null.

Why does this R function not short-circuit properly?

I'm working my way through the Data Science courses at DataCamp. (Not a plug.) One of the practice lessons has the following completed solution:
# logs is available in your workspace
extract_info <- function(x, property = "success", include_all = TRUE) {
info <- c()
for (log in x) {
if (include_all || !log$success) {
info <- c(info, log[[property]])
}
}
return(info)
}
# Call extract_info() on logs, no additional arguments
extract_info(logs)
# Call extract_info() on logs, set include_all to FALSE
extract_info(logs, include_all = FALSE)
The first call (extract_info(logs)) works as I would expect it to: it returns a vector containing all the log entries (regardless of the value of log$success).
The second call (extract_info(logs, include_all = FALSE)) does not return the results I would expect. It returns a vector containing only those results where log$success evaluates to FALSE.
It seems to me that the use of the || operator should cause the if block to short-circuit, and the second call should return nothing. From what I can tell, R evaluates expressions from left to right; but this looks like it's evaluating from right to left.
Can someone explain what's going on here?
(According to the site, this is the correct solution, and there's nothing wrong with the code. I want to know why it works the way it does. Even if the answer is that I'm overlooking something painfully obvious and stupid.)
Well || is the "or" operator. You don't short circuit the "or" operator with a FALSE value; you basically ignore that parameter and just look at the next one because you are looking for any TRUE value.
Assume a is a boolean value. These should be equivalent (<==>).
# or
FALSE || a <==> a
TRUE || a <==> TRUE
# and
TRUE && a <==> a
FALSE && a <==> FALSE
It seems like this was a temporary confusion.
|| is OR and so if either condition evaluates to TRUE, the compound expression evaluates to TRUE. If include_all was TRUE, you could short-circuit the expression, but when include_all is FALSE, you must wait to see what the other part is.

What is the proper idiomatic way of checking if a map has no elements in coffeescript?

since a code example is worth a thousand words:
console.log(#searchEnginesMap, {}, #searchEnginesMap == {}, #searchEnginesMap is {}, #searchEnginesMap.empty?, #searchEnginesMap.length)
returns:
{} {} false false false undefined
what's the correct syntax to get a true value for this? (or how should I correctly check if I have a map with zero elements?)
EDIT: extra credit:
how do you compare these two dictionaries to have them be the same (by value, not be reference):
a = {"foo":"bar?q=%s","baz":"qux?q=%s"}
b = {"foo":"bar?q=%s","baz":"qux?q=%s"}
so I need to know what I can use to get get true while comparing these?
Thanks in advance.
There is no CoffeeScript magic solution here. If you want to know if an Object is empty then you have to count the keys. You could use Object.keys:
if Object.keys(obj).length == 0
# obj is empty
Or you could use a loop:
if (true for v of obj).length == 0
# obj is empty
The for ... of loop version could be wrapped in a short-circuiting function without much effort.
I would probably wimp out and grab Underscore or Lodash so that I could use _.isEmpty:
if _(obj).isEmpty()
# obj is empty
That would also solve your second problem because you'd get _.isEqual too:
_(foo: "bar?q=%s", baz: "qux?q=%s").isEqual(baz: "qux?q=%s", foo: "bar?q=%s")
# true
Underscore demo: http://jsfiddle.net/ambiguous/Jad6e/

Simple question about operator ||

HEllo,
i try to do that in FlashBuilder (FlexProject)
protected function btn_detail_view_clickHandler(event:MouseEvent):void
{
CurrentState="Statistiques" || "PartMarche";
}
But it's not working, i guess this is not the right syntax but what's the right syntax ? Thanks
PS: i want to when the state is equal to "statistiques" or "partMarche" when i click on the button, that the current state changes to Detail view ;)
In ECMAScript languages, || is a short-circuit operator that will return the left-hand side expression result if it evaluates to a "truthy" value, or the right-hand side expression result otherwise. Non-empty strings always evaluate to truthy values, so the left-hand expression will always be returned here. The equivalent long-hand code to your example is:
if ("Statistiques")
CurrentState = "Statistiques";
else
CurrentState = "PartMarche";
This type of short circuit operator is used to set defaults to variables in certain situations:
CurrentState = PreviousState || "Some string";
In that example, if PreviousState is null or false or an empty string, CurrentState would be set to "Some string". If PreviousState is a string like "Some other string", CurrentState would be set to "Some other string".
Thanks for clarifying what you want to do. For checking what CurrentState is, you need to test it with an if condition:
if (CurrentState == "Statistiques" || CurrentState == "PartMarche")
{
// Of course, use the actual name of your detail view here
CurrentState = "DetailView";
}
Ok in fact i need to remove the .Statistiques to that code works in all the states
click.Statistiques="btn_detail_view_clickHandler(event)"
Sorry i just went too fast by myself instead of finishing the tutorial.
Your answers will prevent me to ask the next question ! thank you ;)

Resources