Sunday, September 2, 2007

Multi-assignments (conditional)

bool flag
var a, b, c

if (flag) {
a = x1
b = y1
c = z1
} else {
a = x2
b = y2
c = z2
}
// I see a=, b=, c= twice. Having a multicase in place of binary option, the number of variables will multiply.
// The second looks shorter but we still see redundancy -- the condition is checked for every variable.
a = (flag) ? x1 : x2
b = (flag) ? y1 : y2
c = (flag) ? z1 : z2


//The ideal would be something like
(a, b, c) <= flag ? (x1, y1, z1) : (x2, y2, z2)

for the multiple cases:
a,b,c = switch (flag)
case 1: x1, y1, z1;
case 2: x2, y2, z2;
case 3: x3, y3, z3;
...
// Is it implemented in Python?


This is how the thing is done in JavaScript:
var Helper = function(a, b, c) {this.a = a; this.b = b; this.c = c}
var helper = (area == "") ? new Helper(1,2,3) : new Helper(4,5,6)
log(helper.a)
We still have to submit the object constructor name for all the value sets. Is it better than multiple condition checks?

No comments: