Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary/Octal/Hexadecimal numbers #573

Merged
merged 1 commit into from
May 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}