@@ -4,14 +4,15 @@ function build (schema) {
4
4
/*eslint no-new-func: "off"*/
5
5
var code = `
6
6
'use strict'
7
-
7
+ const properties = ${ JSON . stringify ( schema . properties ) }
8
8
${ $asString . toString ( ) }
9
9
${ $asStringSmall . toString ( ) }
10
10
${ $asStringLong . toString ( ) }
11
11
${ $asNumber . toString ( ) }
12
12
${ $asNull . toString ( ) }
13
13
${ $asBoolean . toString ( ) }
14
14
${ $asRegExp . toString ( ) }
15
+ ${ $coerce . toString ( ) }
15
16
`
16
17
var main
17
18
@@ -131,11 +132,66 @@ function $asRegExp (reg) {
131
132
return '"' + reg + '"'
132
133
}
133
134
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
+
134
187
function buildObject ( schema , code , name ) {
135
188
code += `
136
189
function ${ name } (obj) {
137
190
var json = '{'
138
191
`
192
+ if ( schema . patternProperties ) {
193
+ code += addPatternProperties ( schema . patternProperties )
194
+ }
139
195
140
196
var laterCode = ''
141
197
0 commit comments