diff --git a/README.md b/README.md index 63e784f..e4186ff 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,7 @@ A standalone string cannot be modified, i.e. `data = 'a'; ajv.validate(schema, d - `toLowerCase`: convert to lower case - `toUpperCase`: convert to upper case - `toEnumCase`: change string case to be equal to one of `enum` values in the schema +- `normalizeSpaces`: replace all multiple white spaces with a single white space in a string Transformations are applied in the order they are listed. diff --git a/spec/transform.spec.ts b/spec/transform.spec.ts index 92b32d2..da05baf 100644 --- a/spec/transform.spec.ts +++ b/spec/transform.spec.ts @@ -131,6 +131,43 @@ describe('keyword "transform"', () => { }) ajvs.forEach((ajv, i) => { + it(`should transform normalizeSpaces #${i}`, () => { + let schema, data + + data = [" normalize object to test "] + schema = {type: "array", items: {type: "string", transform: ["normalizeSpaces"]}} + ajv.validate(schema, data).should.equal(true) + data.should.deep.equal([" normalize object to test "]) + + data = ["normalize"] + schema = {type: "array", items: {type: "string", transform: ["normalizeSpaces"]}} + ajv.validate(schema, data).should.equal(true) + data.should.deep.equal(["normalize"]) + + data = ["normalize object to test"] + schema = {type: "array", items: {type: "string", transform: ["normalizeSpaces"]}} + ajv.validate(schema, data).should.equal(true) + data.should.deep.equal(["normalize object to test"]) + + data = ["normalize object to test"] + schema = {type: "array", items: {type: "string", transform: ["normalizeSpaces"]}} + ajv.validate(schema, data).should.equal(true) + data.should.deep.equal(["normalize object to test"]) + + data = [ + `A tab\t\tanother multiple tabs\t\t\t\tnew line +multiple new lines + + + +Multiple spaces end`, + ] + schema = {type: "array", items: {type: "string", transform: ["normalizeSpaces"]}} + ajv.validate(schema, data).should.equal(true) + data.should.deep.equal([ + "A tab another multiple tabs new line multiple new lines Multiple spaces end", + ]) + it(`shouldn't mutate the transform array of the schema while compiling it #${i}`, () => { const data = {p: " trimObject "} const schema = {type: "object", properties: {p: {type: "string", transform: ["trimLeft"]}}} diff --git a/src/definitions/transform.ts b/src/definitions/transform.ts index af4ae29..296a0c3 100644 --- a/src/definitions/transform.ts +++ b/src/definitions/transform.ts @@ -10,6 +10,7 @@ type TransformName = | "toLowerCase" | "toUpperCase" | "toEnumCase" + | "normalizeSpaces" interface TransformConfig { hash: Record @@ -26,6 +27,7 @@ const transform: {[key in TransformName]: Transform} = { toLowerCase: (s) => s.toLowerCase(), toUpperCase: (s) => s.toUpperCase(), toEnumCase: (s, cfg) => cfg?.hash[configKey(s)] || s, + normalizeSpaces: (s) => s.replace(/[\s\t\n]+/g, " "), } const getDef: (() => CodeKeywordDefinition) & {