Structuring a before/after conditional - language-agnostic

When I need a conditional to determine whether a block before or after a statement gets executed, this always leads to repeated code. I either end up with evaluating the condition twice, or repeating the block of code.
Even if this block is just a single function call, it doesn't exactly add to readability.
if( condition ) {
BLOCK-A
}
BLOCK-B
if ( !condition ) {
BLOCK-C
}
or
if( condition ) {
BLOCK-A
BLOCK-B
} else {
BLOCK-B
BLOCK-C
}
Is there a clearer way to structure code like this?

Of your options I would do it this way:
if( condition ) {
BLOCK-A
BLOCK-B
} else {
BLOCK-B
BLOCK-C
}
This will avoid evaluating the condition multiple times as you state in your question.
However, ideally I would try and avoid this kind of structuring all together as it couples the code up and can make changes further down the line difficult. Someone could change something in BLOCK-B for example in one place and not in another. Possibly moving Block-B into it's own function/method etc would be prudent.
Personally I would do something like this
function BlockB()
{
//code from block b
}
function FirstCondition()
{
//BLOCK-A code
BlockB()
}
function SecondCondition()
{
//BLOCK-C code
BlockB()
}
if( condition ) {
FirstCondition()
} else {
SecondCondition()
}

It sounds like BLOCK-B has two similar uses. Consider abstracting it out into its own area
function D {
BLOCK-B
}
if( condition ) {
BLOCK-A
function D
} else {
function D
BLOCK-C
}

Related

Is it possible to only give one argument to function with two parameters?

I have kinda a wierd question. I'm working on removing redundance from my code, and I have two functions which are basically the same, except one of the functions have two parameters and the other one only have one.
I'm wondering if it's possible to "skip" one of the parameters when the function is called, in order to reduce redundance? The functions in this case is in VueJS. Here are the functions:
addTask: function (task, member) {
if (task === '' || member === '') {
alert ('Enter Task & Member!')
}
},
addMember: function (addTeamMember) {
if (addTeamMember === '') {
alert ('Enter Name Of Team Member')
}
So in other words, is it possible to call "addTask" and only parse one argument and skip the other?
You can do it by declaring the variable directly as you can do it in many other languages.
For example:
function addTask(task, member = "") {
}

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

regexp.test() returns boolean but not on 'if' statement - always evaluates to

I am working on a standalone interface.
I have several text boxes, and all have Names and IDs.
If I run this code:
var re = /someregexp/g;
var k ="sometext";
textBoxOne.setText(re.test(k)); //textBoxOne was selected first
The correct result 'true' or 'false' is displayed.
asking for a 'typeof(re.test(k))' correctly returns boolean.
However this code:
if (re.test(k)) {
textBoxTwo.setText("matched.");
} else {
textBoxTwo.setText("NOT matched.");
}
Always goes into the 'else' branch. if (re.test(k) == true) renders the same result.
Looks like a bug to me, anyone else also found this?
Edit: AdamL has pointed out (thanks Adam), in his comments below, that there is more to this than I supposed. I leave my original code below for reference.
The myFunction2() below follows the "matched" branch as you would expect a correctly working regex (so perhaps this can be used to work around the bug):
function myFunction2() {
var k ="sometext";
Logger.log( /ome/g.test(k) );
if ( /ome/g.test(k) ) {
Logger.log("matched.");
} else {
Logger.log("NOT matched.");
}
}
Conversely, as you have observed, the myFunction() below unexpectedly follows through to the "NOT matched" branch.
function myFunction() {
var re = /ome/g;
var k ="sometext";
Logger.log(re.test(k));
if (re.test(k)) {
Logger.log("matched.");
} else {
Logger.log("NOT matched.");
}
}

Checking for same values using if statement in actionscript?

I'm working on a match-3 style puzzle game using Flixel, and so I'm working on checking each row and column to see if there is a match at any given time. However, I have 6 different pieces (as of right now) that are active, and each piece is identified by an integer. Given that, I can check, for each and every single piece, by doing something like this:
public function matchingCheck():void
{
if (piecesArray[0][1] == 1 && piecesArray[1][1] == 1 && piecesArray[2][1] == 1) {
FlxG.log("Yay!");
}
}
However, this is rather unwieldy and would basically cause way too much repetition for my liking.
At the very least, I would like to be able to check if the values in these arrays are equal to one another, without having to specify which value it is. At the very best, I'd love to be able to check an entire row for three (or more) adjacent pieces, but I will settle for doing that part manually.
Thanks for your help!
EDIT: Nevermind, my edit didn't work. It was just checking if piecesArray[2][1] == 1, which makes me a sad panda.
EDIT 2: I've selected the correct answer below - it's not exactly what I used, but it definitely got me started. Thanks Apocalyptic0n3!
You could cut down on that code a little bit by using another function
private function checkValid( arrayOfItemsToCheck:Array, value:* ):Boolean {
for ( var i:Number = 0; i < arrayOfItemsToCheck.length; i++ ) {
if ( arrayOfItemsToCheck[i] != value ) {
return false;
}
}
return true;
}
Then you just do this in your if statement:
if ( checkValid( [ piecesArray[0][1], piecesArray[1][1], piecesArray[2][1] ], 1 ) ) {
FlxG.log("Yay!");
}
That does assume all items need to be equal to 1, though. It's still a lot of code, but it cuts out one set of "= 1 &&" for each check.
How about something like this which would tell you both if a match existed and what match it was:
public function checkForMatch():void{
var rows:int = piecesArray.length;
for(var i:int=0; i<rows; i++){
var match:int = checkRow(piecesArray[i]);
if(match > -1) {
FlxG.log("Yay you matched " + match);
}
}
}
private function ckeckRow(row:Array):int{
if(row[0] == row[1] == row[2]){
return row[0];
}
return -1;
}

Detecting first and last item inside a Groovy each{} closure

I am using Groovy's handy MarkupBuilder to build an HTML page from various source data.
One thing I am struggling to do nicely is build an HTML table and apply different style classes to the first and last rows. This is probably best illustrated with an example...
table() {
thead() {
tr(){
th('class':'l name', 'name')
th('class':'type', 'type')
th('description')
}
}
tbody() {
// Add a row to the table for each item in myList
myList.each {
tr('class' : '????????') {
td('class':'l name', it.name)
td('class':'type', it.type)
td(it.description)
}
}
}
}
In the <tbody> section, I would like to set the class of the <tr> element to be something different depending whether the current item in myList is the first or the last item.
Is there a nice Groovy-ified way to do this without resorting to something manual to check item indexes against the list size using something like eachWithIndex{}?
You could use
if(it == myList.first()) {
// First element
}
if(it == myList.last()) {
// Last element
}
The answer provided by sbglasius may lead to incorrect result like when the list contains redundants elements so an element from inside the list may equals the last one.
I'm not sure if sbglasius could use is() instead of == but a correct answer could be :
myList.eachWithIndex{ elt, i ->
if(i == 0) {
// First element
}
if(i == myList.size()-1) {
// Last element
}
}
if (it.after.value != null) {
......
}
Works for maps