Range in conditionals

You cannot have a range in a conditional? Like this?

<<set $engineering.IC1 = random(100)>><<if $engineering.IC1[40, 50]>>False Alarm. All good<</if>>

I tested, it doesn’t work. Why though?
Or different question, is it possible to define in the … twee/sugarcube(?) engine? Or it is because of JavaScript and JavaScript hasn’t defined that yet?

In my opinion, it would be more redundant and elegant instead of

<<if $engineering.IC1 > 40 && $engineering.IC1 < 50>>

IIRC it’s a JavaScript thing (and with SugarCube built on JavaScript…).
You can always create a JS function in your project (maybe this would work? didn’t test it) that returns a boolean if the value is within the wanted range.

1 Like

Sadly there is little elegant about Javascript. As Manon mentions you can define your own function. In other, more ergonomic, languages I often find myself mapping over ranges. Javascript doesn’t have them as a native concept. But you can useful emulate parts of them.

1 Like

SugarCube is a thin abstraction layer over JavaScript, and in JavaScript Bracket Notation [ ] is used to:

  • access the elements of an Array, using an offset based integer index.
    eg. $array[2] would access the 3rd element of an Array stored in $array
  • access the properties of an object, using a String or Symbol base key value
    eg. $object['abc'] would access the ‘abc’ named property of an Object stored in $object

And JavaScript’s Bracket Notation implementation doesn’t support any form of “range” syntax, the index / key passed to it must be a single value.

So the reasons the Bracket Notation in your example didn’t work as you expected are:

  • the data-type of the value stored in the IC1 property of the object stored in the $engineering variable is an integer.
  • you’re passing multiple values.
1 Like

If you are feeling adventurous, you can define your own range method for numeric variables.

Object.defineProperty(Number.prototype,'range',{
    configurable : true,
    writable     : true,
    value(min,max) {
        return this >= min && this <= max;
    }
});

After doing this, the following will work

<<set $x = 12>>
<<if $x.range(1,20)>> ... <</if>>
2 Likes

Huh! It works. I am blown. Perfect!
Thanks!