-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmultipleOf.ts
43 lines (39 loc) · 1.45 KB
/
multipleOf.ts
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
import { getPrecision } from "../utils/getPrecision";
import { Keyword, JsonSchemaValidatorParams } from "../Keyword";
export const multipleOfKeyword: Keyword = {
id: "multipleOf",
keyword: "multipleOf",
addValidate: ({ schema }) => !isNaN(schema.multipleOf),
validate: validateMultipleOf
};
function validateMultipleOf({ node, data, pointer }: JsonSchemaValidatorParams) {
if (typeof data !== "number") {
return undefined;
}
const { schema } = node;
const valuePrecision = getPrecision(data);
const multiplePrecision = getPrecision(schema.multipleOf);
if (valuePrecision > multiplePrecision) {
// value with higher precision then multipleOf-precision can never be multiple
return node.createError("multiple-of-error", {
multipleOf: schema.multipleOf,
value: data,
pointer,
schema
});
}
const precision = Math.pow(10, multiplePrecision);
const val = Math.round(data * precision);
const multiple = Math.round(schema.multipleOf * precision);
if ((val % multiple) / precision !== 0) {
return node.createError("multiple-of-error", {
multipleOf: schema.multipleOf,
value: data,
pointer,
schema
});
}
// maybe also check overflow
// https://stackoverflow.com/questions/1815367/catch-and-compute-overflow-during-multiplication-of-two-large-integers
return undefined;
}