Setting variable to be undetermined in a ternary operator - ternary-operator

How do I make a variable to stay undefined in a ternary operator?
For example
(var == 2)? var = 3 : (var stays undetermined);

Related

What is the closest to the reverse of the Elvis operator in Groovy?

So I can replace the old ternary operation:
def something = mainThing != null ? mainThing : "gone!"
with the Elvis operator:
def something = mainThing ?: "gone!"
but is there a groovy way to replace the reverse of that:
def keyValuePair = (mainThing != null ? mainThing + "." : "") + "specific=" + value
where I'm using a prefix plus a dot if the prefix exists?
You can use the ?. safe navigation operator to simplify that expression. The operator currently being used (+) makes this hardly relevant, but assuming a method access (which also happens to be more common), you can type:
def keyValuePair = mainThing?.concat('.') ?: "" + "specific=" + value
That uses .concat instead of + for string concatenation [you can use .plus() :-)], and then uses ?:. mainThing?.concat('.') returns null if mainThing is falsey (by Groovy truth terms), or the result of the method call if it is not.

Null Propagation operator in Node.js

I need to do something similar to bar = (foo == null) ? null : foo.bar
Is Null Propagation Operator (?.) available in Node.js? If no, Is this a proposal for the newer version?
[Edit] To add more clarity, I want to avoid NPE when accessing foo.bar (when foo is not defined) and the expression should return a null instead.
Update based on below comment:
The below code will evaluate to the value of foo if foo is falsey (null, undefined, false, empty string, etc), or to foo.bar if foo is not falsey. Like the || operator, the && operator also returns whatever it evaluates last. If foo is falsey, then it will abort evaluation and return the value of foo. If foo is not falsey, then it will continue and evaluate foo.bar and return whatever that is.
foo && foo.bar
Original answer:
You can accomplish this in Javascript using the or operator, ||
The or operator does not necessarily evaluate to a boolean. It returns the last argument that it evaluates the truthiness of.
So, building off of your example, the following code sets foo equal to foo.bar.
foo = null || foo.bar
And the following compares foo to foo.bar (I'm not sure if the double =s in your code was intentional or not. If it was intentional, then consider using triple =s instead)
foo === (null || foo.bar)
This concept is frequently used for setting default values. For example, a function that takes an options argument may do something like this.
options.start = options.start || 0;
options.color = options.color || "red";
options.length = options.length || 10;
Just be careful of one thing. In the last line of the above code, if options.length is 0, then it will be set to 10, because 0 evaluates to false. In that scenario, you probably want to do things the "old-fashioned" way:
options.length = options.length === undefined ? 10 : options.length;
const bar = foo && foo.bar;
This is called Short-circuit evaluation, where second part (part after &&) is only evaluated if the first part is a truthy value.
JavaScript has added support for this, It's called Optional Chaining.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Enumerating Object.keys() in node.js - strange issue

There is an issue with enumerating Object.keys() in node.js that I do not understand. With the following code:
Object.prototype.tuple = function() {
var names = Object.keys(this);
console.log("Dump of names:");
console.log(names);
console.log("FOR loop using indexes:");
for (var k = 0; k < names.length; k++)
{
console.log(names[k]);
}
console.log("FOR loop using enumeration:");
for (var z in names)
{
console.log(z);
}
return this;
};
var x = {a:0, b:0, c:0}.tuple();
I get the following results on the console:
Dump of names:
[ 'a', 'b', 'c' ]
FOR loop using indexes:
a
b
c
FOR loop using enumeration:
0
1
2
tuple
Could somebody explain where does an extra "tuple" come from in the second loop? While defined as function in Object.prototype, it is neither an own property of x object, nor included in names array.
I am using node.js version 0.8.20.
The first loop goes over the properties of x (Object.keys() returns only own properties), while the second one goes over the properties or the array names, including the ones up in the prototype chain.
Thanks to Jonathan Lonowski for clarifications.
I think what #Kuba mentioned above is not correct.
Object.keys, Object.getOwnPropertyNames and other similar method would behave different sightly. Their behaviors are related to a property named enumerable.
I am going to dinner with my friends so I can only give you a helpful link illustrating it. So sorry.
https://developer.mozilla.org/en-US/docs/Enumerability_and_ownership_of_properties

Arithmetic operators in JADE

I'm using Jade template engine with NOde.js.
I have two variables:
a = 0.0378
b = 0.1545
in Jade I do:
- var result = a + b*2
and I get a very strange number when I do #{result}
0.03780.309
It seems to concatenate the numbers as strings.
Could someone tell me how can I use arithmetic operators in Jade?
Thanks
Are you sure that a (and also b) is a number and not a string?
If it is a string you will need to to convert it to a number via parseFloat:
- var result = parseFloat(a)+parseFloat(b)*2
h2 Jadeçš„ operation
- var a = 8
- var b = 2
p #{+a+b}
p #{+a-b}
p #{+a*b}
p #{+a/b}

Programming language idiom for "if object.value == some_value then object.value = some_other_value"

I've been wondering myself multiple times if, and if not, why not, there is an idiom/shortcut for the following pseudocode:
if object.value == some_value then object.value = some_other_value
For example, in JavaScript I sometimes write:
if (document.getElementById("toggledDiv").style.display == "block") {
document.getElementById("toggledDiv").style.display = "none";
}
This seems to be rather tedious. Is there a name for this idiom, and is there a more concise syntax for this in common programming languages?
Thank you!
Edit: To be more precise, I don't care about the braces, but about that you have to reference the attribute at least to times. I'd like to have something like that (pseudocode):
test ( object.value ):
if (it > 0) it = 0;
else it -= 1;
e. g.:
test (document.getElementById("toggledDiv").style.display):
if (it == "block") it = "none";
where it is a keyword that references the tested property. I'm just wondering no programming language seems to have implemented that.
Upate:
Okay, in the meantime I have found something which is a little bit short, but only works in JavaScript:
(function(s){
if(s.display=='block')
s.display="none";
else
s.display='block';
})(document.getElementById("toggledDiv").style)
Well, in Haskell, and other FP languages, conditionals, like ternary operators, are first-class expressions, so you can float the assignment out,
a = if x == y then x else z
Making the code a lot cleaner.
I don't know of any languages that support it out of the box, but there are a number that support defining new operators. In theory, you could write something like the following (in psuedo-code)
operator <T> T toggle(T value, T[] values) {
for(int i=0; i<values.size(); i++) {
if(value == values[i]) {
if(values.size() > (i+1)) {
return values[i+1]
} else {
return values[0]
}
}
}
error "value $value not found in value list $values"
}
Assuming my psuedo-code is correct, this would allow you to do the following:
v = true;
v = v toggle [true, false] ; // v == false
v = v toggle [true, false] ; // v == true (loops to beginning of list
v = v toggle [false, true, true] ; // v == true, since true is both the 2nd and 3rd elements of the list
You could also two versions:
One that, if the values isn't in the list, returns the original value
One that, if the values isn't in the list, throws an error (what my version did)
The former would be less of a toggle and more of... what you asked for, I guess. I was basing the code off the toggle use case from the previous note about css/block/none, where toggle is the more common behavior.
Assuming the language supports it, you could write a toggle= operator too:
v toggle= ['none', 'block']
In JavaScript you can do:
var d = document.getElementById("toggledDiv");
if (d.style.display == "block") d.style.display = "none";

Resources