Skip to content

Commit 0ca83d0

Browse files
committed
Make division by zero checks consistently NaN
1 parent 3baca17 commit 0ca83d0

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

defaultMethods.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ const defaultMethods = {
7878
if (data[0] && typeof data[0] === 'object') return Number.NaN
7979
let res = +data[0]
8080
for (let i = 1; i < data.length; i++) {
81-
if (data[i] && typeof data[i] === 'object') return Number.NaN
81+
if ((data[i] && typeof data[i] === 'object') || !data[i]) return Number.NaN
8282
res /= +data[i]
8383
}
8484
return res
@@ -953,8 +953,14 @@ defaultMethods['-'].compile = function (data, buildState) {
953953
}
954954
// @ts-ignore Allow custom attribute
955955
defaultMethods['/'].compile = function (data, buildState) {
956-
if (Array.isArray(data)) return `(${data.map(i => numberCoercion(i, buildState)).join(' / ')})`
957-
return `(${buildString(data, buildState)}).reduce((a,b) => (+precoerceNumber(a))/(+precoerceNumber(b)))`
956+
if (Array.isArray(data)) {
957+
return `(${data.map((i, x) => {
958+
let res = numberCoercion(i, buildState)
959+
if (x) res = `(${res}||NaN)`
960+
return res
961+
}).join(' / ')})`
962+
}
963+
return `(${buildString(data, buildState)}).reduce((a,b) => (+precoerceNumber(a))/(+precoerceNumber(b) || NaN))`
958964
}
959965
// @ts-ignore Allow custom attribute
960966
defaultMethods['*'].compile = function (data, buildState) {

suites/divide.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,5 +170,17 @@
170170
"rule": { "/": [1, [1]] },
171171
"result": { "error": "NaN" },
172172
"data": null
173+
},
174+
{
175+
"description": "Any division by zero should return NaN",
176+
"rule": { "/": [1, 0] },
177+
"result": { "error": "NaN" },
178+
"data": null
179+
},
180+
{
181+
"description": "Any division by zero should return NaN (2)",
182+
"rule": { "/": [8, 2, 0] },
183+
"result": { "error": "NaN" },
184+
"data": null
173185
}
174186
]

0 commit comments

Comments
 (0)