Question

Quite often I find myself in need of writing stuff similar to:

_parsedBetData["prizeLevel"] = params["prizeLevel"] == null ? "default" : params["prizeLevel"]; 

I am curious if there is a better way to do this? My main concern is that I have to write the params["prizeLevel"] twice.

Of course this could be extracted to a function similar to:

_parsedBetData["prizeLevel"] = defaultIfNull(params["prizeLevel"], "foo");

function defaultIfNull(o:*, default:*):* {
    return o == null ? default : o;
}

But then I would have to have access to this function from wherever I want to do this checkup. Thus I'm wondering if there's some smart way of solving this issue. Maybe with the help of some kind of bit-magic? Or is prototyping/dynamic something appliable here?

The best solution I have come up with this far is to make a macro inside the code IDE that makes some specific keyboard combination write this. But I bet someone has a better idea.

Was it helpful?

Solution

This is perhaps the syntax you're looking for:

_parsedBetData["prizeLevel"] = params["prizeLevel"] || "default";

To set _parsedBetData["prizeLevel"] to default if it is null, you can do

_parsedBetData["prizeLevel"] ||= "default";

This might not do exactly what you want, since an empty string evaluates to false also.

OTHER TIPS

Maybe the logical OR assignment is what you're looking for :)

You could do

params["prizeLevel"] ||= "default";

If you want it to be in some other variable, then use a simple OR operator

_parsedBetData["prizeLevel"] = params["prizeLevel"] || "default";

--EDIT--

Both 32bitkid and cleong are right. You should use logical operators, not the bitwise ones.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top