Last active
February 17, 2024 12:40
-
-
Save fvdm/b56a83c7299466a92c9ba5b3fb34b966 to your computer and use it in GitHub Desktop.
HomeyScript to parse an integer from any argument type within a flow. The result is provided in the `value` tag. You can optionally set a different output type: `number` (default), `string` or `bool`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Parse the argument to an integer of `number` type. | |
* Optionally you can enforce the output type to `number` (default), `string` or `bool`. | |
* The result is provided in the `value` tag. | |
* | |
* @example '22:00' -> 22 | |
* @example '22:00 string' -> '22' | |
* @example '22:00 bool' -> true | |
* @example '0 bool' -> false | |
* | |
* @see {@link https://gist.github.com/fvdm/b56a83c7299466a92c9ba5b3fb34b966} | |
*/ | |
args[0] = args[0] || 0; | |
const int = /^(\d+)/.exec( `${args[0]}` ); | |
const type = / (number|string|bool)$/.exec( `${args[0]}` ); | |
const num = parseInt( int[1], 10 ); | |
let result; | |
switch ( type?.[1] ) { | |
case 'number': result = num; break; | |
case 'string': result = int[1]; break; | |
case 'boolean': result = (num > 0); break; | |
default: result = num; break; | |
} | |
// delete the tag for type change | |
await tag( 'value', null ); | |
await tag( 'value', result ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment