-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathindex.js
43 lines (34 loc) · 1.01 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const genfun = require('generate-function')
const schema = require('./lib/schema')
const anyDefaults = require('./lib/any')
const ops = require('./lib/ops')
exports = module.exports = compile
exports.inferRawSchema = schema.inferRawSchema
exports.jsonSchemaToRawSchema = schema.jsonSchemaToRawSchema
exports.from = from
function from (obj, opts) {
return compile(schema.inferRawSchema(obj), opts)
}
function compile (jsonSchema, opts) {
if (!opts) opts = {}
const isRawSchema = typeof jsonSchema.type === 'number'
const rawSchema = isRawSchema
? jsonSchema
: schema.jsonSchemaToRawSchema(jsonSchema)
const { name } = ops(opts)
const any = anyDefaults(opts)
const gen = genfun()
gen.scope.console = console
// just to reserve these symbols
gen.sym(name)
gen.sym('ptr')
gen.sym('parseString')
gen.sym('parseNumber')
gen(`function parse (${name}, ptr) {`)
gen('if (!ptr) ptr = 0')
any(gen, null, rawSchema)
gen('}')
const parse = gen.toFunction()
parse.pointer = 0
return parse
}