uniqueItems.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
  2. import type KeywordCxt from "../../compile/context"
  3. import {checkDataTypes, getSchemaTypes, DataType} from "../../compile/validate/dataType"
  4. import {_, str, Name} from "../../compile/codegen"
  5. import equal = require("fast-deep-equal")
  6. export type UniqueItemsError = ErrorObject<
  7. "uniqueItems",
  8. {i: number; j: number},
  9. boolean | {$data: string}
  10. >
  11. const error: KeywordErrorDefinition = {
  12. message: ({params: {i, j}}) =>
  13. str`should NOT have duplicate items (items ## ${j} and ${i} are identical)`,
  14. params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`,
  15. }
  16. const def: CodeKeywordDefinition = {
  17. keyword: "uniqueItems",
  18. type: "array",
  19. schemaType: "boolean",
  20. $data: true,
  21. error,
  22. code(cxt: KeywordCxt) {
  23. const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt
  24. if (!$data && !schema) return
  25. const valid = gen.let("valid")
  26. const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : []
  27. cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`)
  28. cxt.ok(valid)
  29. function validateUniqueItems(): void {
  30. const i = gen.let("i", _`${data}.length`)
  31. const j = gen.let("j")
  32. cxt.setParams({i, j})
  33. gen.assign(valid, true)
  34. gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j))
  35. }
  36. function canOptimize(): boolean {
  37. return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array")
  38. }
  39. function loopN(i: Name, j: Name): void {
  40. const item = gen.name("item")
  41. const wrongType = checkDataTypes(itemTypes, item, it.opts.strict, DataType.Wrong)
  42. const indices = gen.const("indices", _`{}`)
  43. gen.for(_`;${i}--;`, () => {
  44. gen.let(item, _`${data}[${i}]`)
  45. gen.if(wrongType, _`continue`)
  46. if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`)
  47. gen
  48. .if(_`typeof ${indices}[${item}] == "number"`, () => {
  49. gen.assign(j, _`${indices}[${item}]`)
  50. cxt.error()
  51. gen.assign(valid, false).break()
  52. })
  53. .code(_`${indices}[${item}] = ${i}`)
  54. })
  55. }
  56. function loopN2(i: Name, j: Name): void {
  57. const eql = cxt.gen.scopeValue("func", {
  58. ref: equal,
  59. code: _`require("ajv/dist/compile/equal")`,
  60. })
  61. const outer = gen.name("outer")
  62. gen.label(outer).for(_`;${i}--;`, () =>
  63. gen.for(_`${j} = ${i}; ${j}--;`, () =>
  64. gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => {
  65. cxt.error()
  66. gen.assign(valid, false).break(outer)
  67. })
  68. )
  69. )
  70. }
  71. },
  72. }
  73. export default def