If you can keep it a one-liner. I’m not certain that’s the case here though.
Which ever one you want to write the oneliner for. Given the function above I’m guessing you are using JS Scripting so that would be SCRIPT ECMAScript (ECMAScript 262 Edition 11)
. Look at the doc for JS Scripting for how to construct a one-liner.
I assume 230
is your voltage.
First, as documented here:
The input value is injected into the script context as a string variable input
.
So you’re not going to do math with it.
Secondly you cannot simply cast a primitive number to make it into a QuantityType
. In fact, QuantiyType
isn’t really even a thing in JS Scripting. As documented here create a Quantity
in JS Scripting:
var qty = Quantity('5.75 m');
Finally, as documented here you can’t do math with the regular operations.
What I don’t know is how Quantity
handles incompatible units. Is it smart enough to convert a A * V
calculation into W
? I don’t know. Ampere and Volt are not the same type of unit. But the library is pretty flexible so it just might work. If you want to give it a try you’ll first need to parse data
into a Quantity
and parse 230 V
into a Quantity
and call multiply()
to perform the operation.
You’ll also need to return it as a String as documented here:
The result of the transformation is provided by the script as its return value. It can be null
, a string , or a value of a type that properly implements .toString()
.
Note that since you are in a recent OH 4, you can create this transformation through MainUI under Settings → Transformations.
(function(ampStr) {
if(ampStr == "NULL" || ampStr == "UNDEF") return ampStr;
var amp = Quantity(ampStr);
var volts = Quantity("230 V");
return amp.multiply(volts).toString();
})(input)
If that doesn’t work, you’ll need to strip the unit from ampStr. Luckily, parseFloat
will stop at the first character that isn’t a part of a floating point number instead of generating an error. Then append the new units on the return value.
(function(ampStr) {
if(ampStr == "NULL" || ampStr == "UNDEF") return ampStr;
var amp = parseFloat(ampStr);
return amp * 230 + ' W';
})(input)