Skip to content

Commit

Permalink
Binary/Octal/Hexadecimal numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
bigbug committed May 3, 2022
1 parent b97c9d7 commit 7b4c810
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/numeric-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ __Signature:__ `$number(arg)`
Casts the `arg` parameter to a number using the following casting rules
- Numbers are unchanged
- Strings that contain a sequence of characters that represent a legal JSON number are converted to that number
- Hexadecimal numbers start with `0x`, Octal numbers with `0o`, binary numbers with `0b`
- Boolean `true` casts to `1`, Boolean `false` casts to `0`
- All other values cause an error to be thrown.

If `arg` is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of `arg`.

__Examples__
- `$number("5")` => `5`
- `$number("0x12")` => `0x18`
- `["1", "2", "3", "4", "5"].$number()` => `[1, 2, 3, 4, 5]`


Expand Down
2 changes: 2 additions & 0 deletions src/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -1202,6 +1202,8 @@ const functions = (() => {
result = arg;
} else if (typeof arg === 'string' && /^-?[0-9]+(\.[0-9]+)?([Ee][-+]?[0-9]+)?$/.test(arg) && !isNaN(parseFloat(arg)) && isFinite(arg)) {
result = parseFloat(arg);
} else if (typeof arg === 'string' && /^(0[xX][0-9A-Fa-f]+)|(0[oO][0-7]+)|(0[bB][0-1]+)$/.test(arg)) {
result = Number(arg);
} else if (arg === true) {
// boolean true casts to 1
result = 1;
Expand Down
6 changes: 6 additions & 0 deletions test/test-suite/groups/function-number/case031.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"expr": "$number('0x12')",
"dataset": null,
"bindings": {},
"result": 18
}
6 changes: 6 additions & 0 deletions test/test-suite/groups/function-number/case032.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"expr": "$number('0B101')",
"dataset": null,
"bindings": {},
"result": 5
}
6 changes: 6 additions & 0 deletions test/test-suite/groups/function-number/case033.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"expr": "$number('0O12')",
"dataset": null,
"bindings": {},
"result": 10
}

0 comments on commit 7b4c810

Please sign in to comment.