Skip to content

Commit 3b8da57

Browse files
committed
Added patternProperties support
1 parent 6053c63 commit 3b8da57

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

index.js

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,15 @@ function build (schema) {
44
/*eslint no-new-func: "off"*/
55
var code = `
66
'use strict'
7-
7+
const properties = ${JSON.stringify(schema.properties)}
88
${$asString.toString()}
99
${$asStringSmall.toString()}
1010
${$asStringLong.toString()}
1111
${$asNumber.toString()}
1212
${$asNull.toString()}
1313
${$asBoolean.toString()}
1414
${$asRegExp.toString()}
15+
${$coerce.toString()}
1516
`
1617
var main
1718

@@ -131,11 +132,66 @@ function $asRegExp (reg) {
131132
return '"' + reg + '"'
132133
}
133134

135+
function $coerce (value, type) {
136+
if (type === 'string') {
137+
return String(value)
138+
} else if (type === 'number') {
139+
return Number(value)
140+
} else if (type === 'boolean') {
141+
return Boolean(value)
142+
} else if (type === 'object') {
143+
return {}
144+
} else if (type === 'array') {
145+
return []
146+
} else {
147+
throw new Error('Cannot coerce ' + value + ' to ' + type)
148+
}
149+
}
150+
151+
function addPatternProperties (pp) {
152+
let code = `
153+
var keys = Object.keys(obj)
154+
for (var i = 0; i < keys.length; i++) {
155+
if (properties[keys[i]]) continue
156+
`
157+
Object.keys(pp).forEach(regex => {
158+
var type = pp[regex].type
159+
if (type === 'integer') type = 'number'
160+
code += `
161+
if (/${regex}/.test(keys[i])) {
162+
`
163+
if (type === 'object') {
164+
code += `
165+
json += $asString(keys[i]) + ':{},'
166+
`
167+
} else if (type === 'array') {
168+
code += `
169+
json += $asString(keys[i]) + ':[],'
170+
`
171+
} else {
172+
code += `
173+
json += $asString(keys[i]) + ':' + $as${type[0].toUpperCase() + type.slice(1)}($coerce(obj[keys[i]], '${type}')) + ','
174+
`
175+
}
176+
code += `
177+
}
178+
`
179+
})
180+
code += `
181+
}
182+
if (Object.keys(properties).length === 0) json = json.substring(0, json.length - 1)
183+
`
184+
return code
185+
}
186+
134187
function buildObject (schema, code, name) {
135188
code += `
136189
function ${name} (obj) {
137190
var json = '{'
138191
`
192+
if (schema.patternProperties) {
193+
code += addPatternProperties(schema.patternProperties)
194+
}
139195

140196
var laterCode = ''
141197

0 commit comments

Comments
 (0)