Skip to content

Commit cb736a2

Browse files
authored
Fix 604 (#605)
* Revert "improve performance of asNumber (#595)" This reverts commit 07a9bcc. * add regression test Signed-off-by: Matteo Collina <[email protected]> --------- Signed-off-by: Matteo Collina <[email protected]>
1 parent 75c7d62 commit cb736a2

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

lib/serializer.js

+6-9
Original file line numberDiff line numberDiff line change
@@ -50,17 +50,14 @@ module.exports = class Serializer {
5050
}
5151

5252
asNumber (i) {
53-
if (typeof i !== 'number') {
54-
i = Number(i)
55-
}
56-
// NaN !== NaN
57-
if (i !== i) { // eslint-disable-line no-self-compare
53+
const num = Number(i)
54+
if (Number.isNaN(num)) {
5855
throw new Error(`The value "${i}" cannot be converted to a number.`)
56+
} else if (!Number.isFinite(num)) {
57+
return null
58+
} else {
59+
return '' + num
5960
}
60-
if (i === Infinity || i === -Infinity) {
61-
return 'null'
62-
}
63-
return '' + i
6461
}
6562

6663
asBoolean (bool) {

test/fix-604.test.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
'use strict'
2+
3+
const t = require('tap')
4+
const fjs = require('..')
5+
const schema = {
6+
type: 'object',
7+
properties: {
8+
fullName: { type: 'string' },
9+
phone: { type: 'number' }
10+
}
11+
}
12+
13+
const input = {
14+
fullName: 'Jone',
15+
phone: 'phone'
16+
}
17+
18+
const render = fjs(schema)
19+
20+
try {
21+
render(input)
22+
} catch (err) {
23+
t.equal(err.message, 'The value "phone" cannot be converted to a number.')
24+
}

0 commit comments

Comments
 (0)