UNPKG

1.07 kBPlain TextView Raw
1import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
2import type {KeywordCxt} from "../../compile/validate"
3import {_, str} from "../../compile/codegen"
4
5export type MultipleOfError = ErrorObject<
6 "multipleOf",
7 {multipleOf: number},
8 number | {$data: string}
9>
10
11const error: KeywordErrorDefinition = {
12 message: ({schemaCode}) => str`must be multiple of ${schemaCode}`,
13 params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`,
14}
15
16const def: CodeKeywordDefinition = {
17 keyword: "multipleOf",
18 type: "number",
19 schemaType: "number",
20 $data: true,
21 error,
22 code(cxt: KeywordCxt) {
23 const {gen, data, schemaCode, it} = cxt
24 // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
25 const prec = it.opts.multipleOfPrecision
26 const res = gen.let("res")
27 const invalid = prec
28 ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
29 : _`${res} !== parseInt(${res})`
30 cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)
31 },
32}
33
34export default def