This Squirrel code defines the `When` class and `when` function, enabling conditional logic functionality. The `When` class includes methods like `is` (equal to) and `isNot` (not equal to). If conditions are met, corresponding actions are executed and results are recorded, with only the first matching action triggered. Otherwise, all non-matching cases are handled, and the final result is returned.
class When {
value = null;
found = false;
result = null;
constructor(value) {
this.value = value;
}
function is(expected, action) {
if (!found && value == expected) {
found = true;
result = action();
}
return this;
}
function isNot(expected, action) {
if (!found && value != expected) {
found = true;
result = action();
}
return this;
}
function isType(typeName, action) {
if (!found && typeof value == typeName) {
found = true;
result = action();
}
return this;
}
function isNull(action) {
if (!found && value == null) {
found = true;
result = action();
}
return this;
}
function inRange(min, max, action) {
if (!found && value >= min && value <= max) {
found = true;
result = action();
}
return this;
}
function match(condition, action) {
if (!found && condition(value)) {
found = true;
result = action();
}
return this;
}
function otherwise(action) {
if (!found) {
result = action();
}
return result;
}
}
function when(value) {
return When(value);
}
Here is an example
local x = 65;
local result = when(x)
.isNull(@()"is Null")
.isType("float", @()"Not Float")
.is(100, @()"Max")
.inRange(0, 35, @()"0~35")
.inRange(35, 70, @()"35~70")
.match(@(v) v * 2 > 150 && v < 80, @()"75~80")
.otherwise(@()">80");
print(result); // out 0~35