Simple question about operator || - apache-flex

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

Related

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

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

how stacks are formed and value from a method return when the method has TWO recursive calls of itself from within itself

I have tried creating stacks for recursive inorder,preorder,postoreder traversal for binary tree and I was doing it pretty well. In other cases like, for example, for a test case my answer should be 'true',say.And, for example,
boolean method(root)
{
// more code
method(root.left());
method(root.right());
}
,somewhere,the call of method(root.left()) returns false and a call of method(root.right()) returns true that should be our answer. But since call of method(root.left() ) completes first and somewhere, in between it's execution, it might have returned false. then how do we get our result true from method(root.right())?? I think it is related to how stacks are formed and values from a method are returned when recursive calls ,in this way, happen.Explain it and correct me if I am wrong.
You need to return values. The method need to make use of the returned values in its logic to stop/continue the search.
You need to have that the base cases return either true of false. Then when doing the first recursive call you need only do the first if the result is true. The second recursive call would be the result of the method if it's needed. Thus you are looking at something like this:
boolean method(root)
{
if( root == null ) { // base case 1
return false;
}
if( root.value == someValue ) { // base case 2, what should be a positive
return true;
}
// default search left first and return true if true
if( method(root.left()) ) {
return true;
}
// default search right and return true if true
if( method(root.right()) ){
return true;
}
// return false since neither recursive calls were true
return false;
}
This is very verbose and can be written like this instead:
boolean method(root)
{
return root != null && ( root.value == someValue ||
method(root.left()) ||
method(root.right()));
}
I find the last more readable but novices might find the more verbose first one to be more clear.
In both the callee resumes operation after the first recursive call (which might have had it's share of calls as well) and continues it's logic and recurses on the right side if needed.
Don't care about the system stack. Care about the base case and test them. Then do the simplest of added complexity to do the default case so that you see the problem becoming smaller in the recursive call(s). It's much better going from simple to more complex than to try figuring this stuff out by starting at a large tree looking at whats happening with a very deep recursive round.

Groovy NullObject should be null or not?

This example can be easily tested in the groovy console.
var a is evaluated to not null while b is evaluated to null.
Both are instances of org.codehaus.groovy.runtim.NullObject
def b = null
println b.getClass()
println b == null
def a = null.getClass().newInstance()
println a.getClass()
println a == null
Does anyone knows why?
This is a tricky thing when dealing with reflection code.
Actually I am wondering if this is not a bug. As an explanation... NullObject is a runtime/intermediate kind of Object. If you do anything on null, then NullObject is used. This, and the the implementation of NullObject#equals speaks for a==null returning true. It returns fails, because there is some internal code before that, that is for example determining if compareTo is called instead of equals and such things. Now this piece of code starts with
if (left == right) return true;
if (left == null || right == null) return false;
so null==null will return true, but NullObject==null will return false. On the other hand NullObject should not leak out if possible. Maybe we should fix newInstance() to return null.
I filled http://jira.codehaus.org/browse/GROOVY-5769 for this
In the equals method of NullObject, it only returns true if you are comparing it to null
As an instance of NullObject is not strictly null, it returns false...
Whether NullObject should return true if you call equals against another NullObject is probably a question best asked on the mailing list... I'll have a look and see if I can find any previous question.

Enumeration ids, disallowed in match operation?

I have an Enumeration class, and have extracted "id" values from some of the members and stored them in Int variables. Whether that was a good idea/not is not the question.
What the question is, is why I cant seem to do the following:
Let's say I have s : Int which holds one of these id values ... and I would like to do matching against the actual enumeration values. Something like the following:
s match {
QID.MEM_RD.id => // something
QID.MEM_WRT.id => // something else
}
This seems to give me a failure that "stable identifier is required". So I end up writing code like
if (s == QID.MEM_RD.id)
// something
else if (s == QID.MEM_WRT.ID)
// something else
So .. it's just kind of odd to me that Scala has this nice feature, but appears to force me to go back to an uglier style of coding --- when I would much rather use their match feature.
Any ideas? I guess I can restructure to stop extracting ids ... but it's just the idea that match doesn't allow this that irks me a bit.
(Note: I don't try to store the id values anywhere persistently ... just use them for the duration of program execution.)
-Jay
I think you can use if guards in that case.
s match {
case a if (s == QID.MEM_RD.id) => println("you read!")
case b if (s == QID.MEM_WRT.id) => println("you wrote!")
}
http://programming-scala.labs.oreilly.com/ch03.html#PatternMatching

Simplest way to check if a string converted to a number is actually a number in actionscript

Not sure if this makes sense, but I need to check if a server value returned is actually a number. Right now I get ALL number values returned as strings
ie '7' instead of 7.
What's the simplest way to check if string values can actually be converted to numbers?
The easiest way to do this is to actually convert the string to a Number and test to see if it's NaN. If you look at the Flex API reference, the top-level Number() function says it will return NaN if the string passed to the method cannot be converted to a Number.
Fortunately, Flex (sort of) does this for you, with the isNaN() function. All you need to do is:
var testFlag:Boolean = isNaN( someStringThatMightBeANumber );
If testFlag is false, the string can be converted to a number, otherwise it can't be converted.
Edit
The above will not work if compiling in strict mode. Instead, you will need to first convert to Number and then check for NaN, as follows:
var testFlag:Boolean = isNaN( Number( someStringThatMightBeANumber ) );
Haven't tested this, but this should work:
if( isNaN(theString) ) {
trace("it is a string");
} else {
trace("it is a number");
}
If you are using AS3 and/or strict mode (as pointed out by back2dos), you will need to convert to number first in order for it to compile:
if( isNaN(Number(theString)) ) {
trace("it is a string");
} else {
trace("it is a number");
}
Most of the answers on this question have a major flaw in them. If you take Number(null) or Number(undefined) or Number(""), all will return 0 and will evaluate to "is a number". Try something like this instead:
function isANumber( val:* ):Boolean {
return !(val === null || val === "" || isNaN(val));
}
RegExp path :
function stringIsAValidNumber(s: String) : Boolean {
return Boolean(s.match(/^[0-9]+.?[0-9]+$/));
}
Here is another way to check if value can be converted to a number:
var ob:Object = {a:'2',b:3,c:'string'};
for( var v:* in ob){
var nr:Number = ob[v];
trace(ob[v]+" "+(nr === Number(nr)))
}
this will trace following:
2 true
3 true
string false
You can notice that in actionscript :
trace(int('7')); // will return 7
and
trace(int('a')); // will return 0
So except for zeros, you can actually now if a string is a number or not
this will try to convert your String to a Number, which essentially is a 64 bit floating point number:
var val:Number = Number(sourceString);
if sourceString is not a valid String representation of a Number, val will be NaN (not a number) ... you have check against that value with isNaN ... because val == NaN will return false for a reason that can't quite understand ... you can use int(val) == val to check, whether it is an integral value ...
greetz
back2dos
Put this into any function where you want only numbers to stayjoy_edit1 is a TextInput Object (spark)
//is a number check
if( isNaN(Number(joy_edit1.text)) ) {
joy_edit1.text = "";
return void;
}
function isANumber(__str:String):Boolean
{
return !isNaN(Number(__str));
}
You should use the native solution of Adobe:
parseInt and parseFloat methods.
Also read the isNaN description:
Returns true if the value is NaN(not a number). The isNaN() function
is useful for checking whether a mathematical expression evaluates
successfully to a number. The most common use of isNaN() is to check
the value returned from the parseInt() and parseFloat() functions. The
NaN value is a special member of the Number data type that represents
a value that is "not a number."
Here is a simple implementation:
function isANumber(value:String):Boolean {
return !isNaN(parseFloat(value));
}
typeof('7') == 'string'
typeof(7) == 'number'
Does that help?

Resources