multipleOf.ts 1.0 KB

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