Skip to content

Commit b7edee7

Browse files
committed
Added regex stringify
1 parent 895646c commit b7edee7

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

index.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ function build (schema) {
1111
${$asNumber.toString()}
1212
${$asNull.toString()}
1313
${$asBoolean.toString()}
14+
${$asRegExp.toString()}
1415
`
1516
var main
1617

@@ -36,6 +37,9 @@ function build (schema) {
3637
main = '$main'
3738
code = buildArray(schema, code, main)
3839
break
40+
case 'RegExp':
41+
main = $asRegExp.name
42+
break
3943
default:
4044
throw new Error(`${schema.type} unsupported`)
4145
}
@@ -115,6 +119,19 @@ function $asStringSmall (str) {
115119
return '"' + result + '"'
116120
}
117121

122+
function $asRegExp (reg) {
123+
reg = reg instanceof RegExp ? reg.source : reg
124+
125+
for (var i = 0, len = reg.length; i < len; i++) {
126+
if (reg[i] === '\\' || reg[i] === '"') {
127+
reg = reg.substring(0, i) + '\\' + reg.substring(i++)
128+
len += 2
129+
}
130+
}
131+
132+
return '"' + reg + '"'
133+
}
134+
118135
function buildObject (schema, code, name) {
119136
code += `
120137
function ${name} (obj) {
@@ -223,6 +240,11 @@ function nested (laterCode, name, key, schema) {
223240
json += ${funcName}(obj${key})
224241
`
225242
break
243+
case 'RegExp':
244+
code += `
245+
json += $asRegExp(obj${key})
246+
`
247+
break
226248
default:
227249
throw new Error(`${type} unsupported`)
228250
}

test.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,3 +222,38 @@ buildTest({
222222
}, {
223223
readonly: true
224224
})
225+
226+
test('object with RexExp', (t) => {
227+
t.plan(3)
228+
229+
const schema = {
230+
title: 'object with RegExp',
231+
type: 'object',
232+
properties: {
233+
reg: {
234+
type: 'RegExp'
235+
},
236+
streg: {
237+
type: 'RegExp'
238+
}
239+
}
240+
}
241+
242+
const obj = {
243+
reg: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
244+
streg: '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$'
245+
}
246+
247+
const stringify = build(schema)
248+
const output = stringify(obj)
249+
250+
try {
251+
JSON.parse(output)
252+
t.pass()
253+
} catch (e) {
254+
t.fail()
255+
}
256+
257+
t.equal(obj.reg.source, new RegExp(JSON.parse(output).reg).source)
258+
t.equal(obj.streg, JSON.parse(output).streg)
259+
})

0 commit comments

Comments
 (0)