Opposite of 'else' during a switch or conditional - language-agnostic

I'm wondering if any programming language has an operator like so (ALWAYS is a placeholder--I'm asking what language has something like ALWAYS)
if a
doAStuff()
else if b
doBStuff()
ALWAYS
//runs if a or b is true
win()
else
doElse()
Basically, the opposite of else. It runs if something else in the statement ran.
logically, it would be like this
always = true
if a
doA()
else if b
doB()
else
always = false
doElse()
if always
win()
Does any language have that logic built into a keyword, such as ALWAYS from the first example?

Not really 'language-agnostic'. More like 'find-my-language'. With Forth and Lisp you can add such a construct naturally to the language, and it will work just like existing constructs. I'm not aware of any language that has it by default. If you have a less extensible language than Forth or Lisp, then the natural ways to do this are to use a local function (if you have first-class functions) or to set a flag as you show, or else to factor the code such that both conditions can be treated as pairs without a lot of repetition.
So, in JavaScript:
;(function() {
function both() { win(); more stuff, potentially }
if (a) { doA(); if (b) both() }
else if (b) { doB(); if (a) both() }
else neither()
})()
At upon reading that, it should be clear that the 'both' case is never going to happen in that second block. So this simplifies to:
;(function() {
function both() { win(); more stuff, potentially }
if (a) { doA(); if (b) both() }
else if (b) doB()
else neither()
})()
Which doesn't seem worth the effort. So it seems even less worth a language feature. Why not go further and write this?
if (a) { doA(); if (b) { win(); more stuff, potentially } }
else if (b) doB()
else neither()
If b is an expensive test, just save the result of it. If b must not be tested before a, save both results. Obviously, both tests must always be run anyway.
;(function() {
var a = testA(),
b = testB()
... as above ...
})()
As for the last option, "factor the code such that both conditions can be treated as pairs", what you're looking for is:
if (a && !b) doA()
if (!a && b) doB()
if (a && b) { doA(); doB(); win() } // or no doB() if you really want that
if (!a && !b) neither()
With else if if you like. I'd prefer this option actually in a pattern-matching language. Mercury will even throw an compile-time error if you forget one of the four possible outcomes.

Not sure if this is what you're looking for, but a simple do-while loop will ALWAYS run at least once in Java.

Related

Immutable.js, how to quit search on first find

currently I am doing
var adnetCustomerModel = customersList.find((adnetCustomerModel) => {
return adnetCustomerModel.getId() == customerId;
})
but wasting CPU cycles as I have to continue and traverse the entire list (or so I am assuming that's what happens).
I'd like to quit on first find.
Now I know I can do a filter().first() (which I believe will have same waste of CPU cycles) but is there a better way?
If it was a normal for loop I would just break...
will the return achieve the same effect in immutable.js?
tx for reading,
Sean
Immutable’s find() already returns only the first value for which the predicate returns true. It actually just wraps around the findEntry() method that’s implemented like this:
findEntry(predicate, context, notSetValue) {
var found = notSetValue;
this.__iterate((v, k, c) => {
if (predicate.call(context, v, k, c)) {
found = [k, v];
return false;
}
});
return found;
}
So, you’re not wasting any cycles. :)
Vanilla JavaScript Array.prototype.find() also returns the value of the first element to match the predicate.

[cc creator]Comparison not working

I have an array of Nodes 'flags', and I want to set my object's position at the first object in that array, it works and the object actually gets positioned as intended, but when I make the comparison it fails and logs 'NO'.
The line of code that sets the position works, but the comparison fails, what's wrong here?!
start: function () {
this.node.position = this.flags[0].position;
this.movement();
},
movement: function() {
if (this.node.position == this.flags[0].position) { // Problem
console.log("YES");
}
else {
console.log("No");
Update:
When I do it like this it works:
if (this.node.position.x == this.flags[0].position.x) // or position.y
Well if you write javascript here (and it looks like you do) there're two things you should know:
You can't compare objects with == out of the box
({"a":1} == {"a":1})
Will return false (you may try it yourself in your browser.
As a workaround you could do something like:
function posCompare(p1, p2){
return p1.x === p2.x && p1.y === p2.y;
}
Then use it instead of == for positions
See how I use === instead of ==? Second thing to know is Use only ===. You can learn the difference Which equals operator (== vs ===) should be used in JavaScript comparisons? but I'd keep away from == anywhere. It's slower, it may cause strange errors here and there - just don't use it at all

How to suppress the warning "Assignment within conditional. Did you mean == instead of =?"

With the new ASC 2.0 compiler I get warnings when I code like below:
// (_achievementsFromServer is an Array)
while(item=_achievementsFromServer.pop())
{
// do something with item here
}
The warning reads: "Assignment within conditional. Did you mean == instead of =?"
While in general I appreciate all warnings from the compiler, I'd like to suppress this one in this case because I did not mean == here. I want to pop all items in the array and do something with it until the array is empty.
while( (item=_achievementsFromServer.pop())==true )
seems to work but looks a bit confusing. Any other ideas?
This may seem better.
while(_achievementsFromServer.length > 0) {
var item:Object = _achievementsFromServer.pop();
}
Just like removeChild
var d:DisplayObjectContainer;
while(d.numChildren > 0) {
d.removeChildAt(0);
}
While I was hoping for some other way, I think #AmyBlankenship improved my own suggestion:
while((item=_achievementsFromServer.pop())!=null)
{
//....
}
It's clear and understandable what's going on, and doesn't rely on checking the length of the Array on every iteration.
Googling some more I found a compiler option -compiler.warn-assignment-within-conditional that could be set to false but then you won't be warned anywhere in your project anymore. And I'm not so confident that I never accidently type = instead of ==, so that's not a good solution I think.

Compact if/else statement [AS3]

Really simple question, I just wanted to know if there was a way to write if/else statements with fewer characters, for example I can create an if statement with either:
if (season == "autumn") {
tree.gotoAndStop ("brown leaves");
}
or:
if (season == "autumn") tree.gotoAndStop ("brown leaves");
This uses much less space and makes my code look much prettier. With an if/else statement my options seem to be either:
if (season == "autumn" || season == "winter") {
tree.gotoAndStop ("brown leaves");
} else {
tree.gotoAndStop ("green leaves");
}
or:
gotoAndStop((season == "autumn" || season == "winter")
? "brown leaves" : "green leaves");
Though the second approach isn't always ideal. Do you know any alternatives?
As far as writing your code in a terse manner, you can use all of the following techniques to manually minify your code, but this is a terrible design decision and will likely lead to headaches and/or bodily harm in the future. Don't say I didn't warn you.
if-else:
if (foo) {
bar();
} else {
baz();
}
becomes:
foo?bar():baz()
if:
if (foo) {
bar();
}
becomes:
foo&&bar();
if-not:
if (!foo) {
bar();
}
becomes:
foo||bar();
if with multiple statements:
if (foo) {
bar();
baz();
fizz();
buzz();
}
becomes:
foo&&(bar(),baz(),fizz(),buzz());

Most readable way to write simple conditional check

What would be the most readable/best way to write a multiple conditional check such as shown below?
Two possibilities that I could think of (this is Java but the language really doesn't matter here):
Option 1:
boolean c1 = passwordField.getPassword().length > 0;
boolean c2 = !stationIDTextField.getText().trim().isEmpty();
boolean c3 = !userNameTextField.getText().trim().isEmpty();
if (c1 && c2 && c3) {
okButton.setEnabled(true);
}
Option 2:
if (passwordField.getPassword().length > 0 &&
!stationIDTextField.getText().trim().isEmpty() &&
!userNameTextField.getText().trim().isEmpty() {
okButton.setEnabled(true);
}
What I don't like about option 2 is that the line wraps and then indentation becomes a pain. What I don't like about option 1 is that it creates variables for nothing and requires looking at two places.
So what do you think? Any other options?
if (HasPassword() && HasStation() && HasUserName())
okButton.setEnabled(true);
bool HasPassword() {
return passwordField.getPassword().length > 0;
}
etc.
Note that option 1 does not allow for short circuiting behavior. That is, you calculate the value of all of the conditionals before evaluating the result of the first.
I would modify option 1 so that you're using variable names that actually have a meaning. That is, change the name of "c2" to be something like "stationIDIsEmpty" (and move the NOT into the conditional). That way the conditional is readable without having to glance back and forth for every variable.
So my code would probably look like:
boolean enteredPassword = passwordField.getPassword().length > 0;
boolean stationIDIsEmpty = stationIDTextField.getText().trim().isEmpty();
boolean userNameIsEmpty = userNameTextField.getText().trim().isEmpty();
if (enteredPassword && !stationIDIsEmpty && !userNameIsEmpty) {
okButton.setEnabled(true);
}
I voted for Chris Brandsma's answer.
But just wanted to mention the main issue I have with Option 1 is you are losing the benefit of &&. With option one, although I think it's more readable, you are processing comparisons when they may not be required.
Personally, I like the second way, because I find that using that way can make the predication of the conditionals clear. That is, with that method done properly, you can make the conditional comprehensible by "verablizing" it (whether or not you actually speak it is irrelevant).
That is, with your second option, it becomes clear that your conditional translates roughly as this: "If the password length is greater than zero, AND the stationIDTextField (trimmed) is NOT empty, AND the usernameTextField (trimmed) is NOT empty, then..."
I prefer the following:
if (passwordField.getPassword().length > 0
&& ! stationIDTextField.getText().trim().isEmpty()
&& ! userNameTextField.getText().trim().isEmpty())
{
okButton.setEnabled(true);
}
With this coding style I accomplish two things:
I can easily see that each extra line of the if is part of the condition because of the && (or ||) at the beggining.
I can easily see where the if statement ends because of the { at the next line.
Option1 is prime for applying the refactoring 'Replace temp with Query'. The reason being that someone can stuff in code between the variable is initialized and the check and change the behavior of the code. Or the check might be made with stale values.. an update has been made to the textfields between initialization and checking.
So my attempt at this would be
if (GetPasswordLength() > 0
&& FieldHelper.IsNotEmpty(stationIDTextField)
&& FieldHelper.IsNotEmpty(userNameTextField)
{
okButton.setEnabled(true);
}
FieldHelper is a class with public static methods (also called a Utility class / Static class in C#)