Optimized function 'mp'

Leaner syntax of function `mp` and simplified implementation.
New documentation:
Mapping function `mp`

It addresses a standard task with less code and much flexibility: mapping an arbitrary incoming numeric value into a defined schema of allowed/reasonable ranges.
The numeric value `x` passed as the first parameter is compared to the mprules in the order they are provided as subsequent parameters. If the value matches the criteria, the defined value is returned. Subsequent mprules are skipped. If `x` matches none of the mprules, `x` is returned unchanged. 
```
mp(x mprule1 mprule2 ... mprule<n>)
```

An mprule starts with one of the comparison operators `<`, `>` or `=`, followed by a numeric value `v1`, optionally followed by a second numeric value `v2`:
```
<|>|=v1[ v2]
```

Example 1: `<8 0` - this rule reads: If x is less than 8, return 0.
Example 2: `>100` - this rule reads: If x is greater than 100, return 100. 

Example 3:
```
y=mp(x <8 0 >100)
```
Assigns 0 to y if x is less than 8.
Assigns 100 to y if x is greater than 100.
Assigns x to y for all values of x that do not meet the above criteria (8 to 100).

The above code of example 3 does the same as the following code - with just one line of code and 19 characters less:
```
y=x
if x<8 {
y=0
}
if x>100 {
y=100
}
```

Every of the above mentioned numeric values `x`, `v1` and `v2` can be a literal, an expression or a variable.
This commit is contained in:
Alexander Schliebner 2020-03-07 16:53:49 +01:00 committed by GitHub
parent df43217a18
commit 7df46f051d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1502,30 +1502,27 @@ chknext:
lp=GetNumericResult(lp,OPER_EQU,&fvar1,0);
SCRIPT_SKIP_SPACES
while (*lp!=')') {
char str[SCRIPT_MAXSSIZE];
lp=GetStringResult(lp,OPER_EQU,str,0);
SCRIPT_SKIP_SPACES
char *pstr=str;
pstr++;
char *opp=lp;
lp++;
float fvar2;
pstr=GetNumericResult(pstr,OPER_EQU,&fvar2,0);
while (*pstr==' ') pstr++;
lp=GetNumericResult(lp,OPER_EQU,&fvar2,0);
SCRIPT_SKIP_SPACES
fvar=fvar1;
if ((str[0]=='<' && fvar1<fvar2) ||
(str[0]=='>' && fvar1>fvar2) ||
(str[0]=='=' && fvar1==fvar2))
if ((*opp=='<' && fvar1<fvar2) ||
(*opp=='>' && fvar1>fvar2) ||
(*opp=='=' && fvar1==fvar2))
{
if (*pstr==':') {
pstr++;
while (*pstr==' ') pstr++;
if (*lp!='<' && *lp!='>' && *lp!='=') {
float fvar3;
pstr=GetNumericResult(pstr,OPER_EQU,&fvar3,0);
lp=GetNumericResult(lp,OPER_EQU,&fvar3,0);
SCRIPT_SKIP_SPACES
fvar=fvar3;
} else {
fvar=fvar2;
}
break;
}
while (*lp!='<' && *lp!='>' && *lp!='=' && *lp!=')' && *lp!=SCRIPT_EOL) lp++;
}
len=0;
goto exit;