mirror of
https://github.com/mikefarah/yq.git
synced 2026-07-10 16:55:40 +00:00
Handle int modulo by 0 and add tests
This commit is contained in:
parent
16997769e0
commit
c0fd3fe38b
@ -35,3 +35,38 @@ a: !!float 2
|
||||
b: 2.5
|
||||
```
|
||||
|
||||
## Number modulo - int by zero
|
||||
If the lhs is an int and rhs is a 0 the result is an error.
|
||||
|
||||
Given a sample.yml file of:
|
||||
```yaml
|
||||
a: 1
|
||||
b: 0
|
||||
```
|
||||
then
|
||||
```bash
|
||||
yq '.a = .a % .b' sample.yml
|
||||
```
|
||||
will output
|
||||
```bash
|
||||
Error: cannot modulo by 0
|
||||
```
|
||||
|
||||
## Number modulo - float by zero
|
||||
If the lhs is a float and rhs is a 0 the result is NaN.
|
||||
|
||||
Given a sample.yml file of:
|
||||
```yaml
|
||||
a: 1.1
|
||||
b: 0
|
||||
```
|
||||
then
|
||||
```bash
|
||||
yq '.a = .a % .b' sample.yml
|
||||
```
|
||||
will output
|
||||
```yaml
|
||||
a: !!float NaN
|
||||
b: 0
|
||||
```
|
||||
|
||||
|
||||
@ -68,6 +68,9 @@ func moduloScalars(context Context, target *CandidateNode, lhs *yaml.Node, rhs *
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rhsNum == 0 {
|
||||
return fmt.Errorf("cannot modulo by 0")
|
||||
}
|
||||
remainder := lhsNum % rhsNum
|
||||
|
||||
target.Node.Tag = lhs.Tag
|
||||
|
||||
@ -40,6 +40,22 @@ var moduloOperatorScenarios = []expressionScenario{
|
||||
"D0, P[], (doc)::{a: !!float 2, b: 2.5}\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Number modulo - int by zero",
|
||||
subdescription: "If the lhs is an int and rhs is a 0 the result is an error.",
|
||||
document: `{a: 1, b: 0}`,
|
||||
expression: `.a = .a % .b`,
|
||||
expectedError: "cannot modulo by 0",
|
||||
},
|
||||
{
|
||||
description: "Number modulo - float by zero",
|
||||
subdescription: "If the lhs is a float and rhs is a 0 the result is NaN.",
|
||||
document: `{a: 1.1, b: 0}`,
|
||||
expression: `.a = .a % .b`,
|
||||
expected: []string{
|
||||
"D0, P[], (doc)::{a: !!float NaN, b: 0}\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
skipDoc: true,
|
||||
description: "Custom types: that are really numbers",
|
||||
|
||||
Loading…
Reference in New Issue
Block a user