From dc9f4a0d84b9082605930a2bae2acb197a210bff Mon Sep 17 00:00:00 2001 From: Ivan Tanev Date: Wed, 24 Jun 2020 14:59:55 +0300 Subject: [PATCH 1/2] Handle sparse array positions as undefined --- src/array.js | 14 ++++++++------ test/array.js | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/array.js b/src/array.js index 76c536be4..d06f2312c 100644 --- a/src/array.js +++ b/src/array.js @@ -84,8 +84,10 @@ inherits(ArraySchema, MixedSchema, { originalValue = originalValue || value; - let validations = value.map((item, idx) => { - var path = makePath`${options.path}[${idx}]`; + let validations = new Array(value.length); + for (let idx = 0; idx < value.length; idx++) { + let item = value[idx]; + let path = makePath`${options.path}[${idx}]`; // object._validate note for isStrict explanation var innerOptions = { @@ -97,10 +99,10 @@ inherits(ArraySchema, MixedSchema, { originalValue: originalValue[idx], }; - if (innerType.validate) return innerType.validate(item, innerOptions); - - return true; - }); + validations[idx] = innerType.validate + ? innerType.validate(item, innerOptions) + : true; + } return runValidations({ sync, diff --git a/test/array.js b/test/array.js index a09081702..b5b5a8576 100644 --- a/test/array.js +++ b/test/array.js @@ -202,4 +202,20 @@ describe('Array types', () => { .of(itemSchema) .validate(value); }); + + it('should maintain array sparseness through validation', async () => { + let sparseArray = new Array(2); + sparseArray[1] = 1; + let value = await array().of(number()).validate(sparseArray); + expect(0 in sparseArray).to.be.false() + expect(0 in value).to.be.false() + // eslint-disable-next-line no-sparse-arrays + value.should.eql([,1]); + }); + + it('should validate empty slots in sparse array', async () => { + let sparseArray = new Array(2); + sparseArray[1] = 1; + await array().of(number().required()).isValid(sparseArray).should.become(false); + }); }); From 6d12d2c11c0b40b040f2930b693f257204bff2b2 Mon Sep 17 00:00:00 2001 From: Jason Quense Date: Thu, 25 Jun 2020 10:35:40 -0400 Subject: [PATCH 2/2] Update src/array.js --- src/array.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/array.js b/src/array.js index d06f2312c..3313c0cd0 100644 --- a/src/array.js +++ b/src/array.js @@ -84,6 +84,7 @@ inherits(ArraySchema, MixedSchema, { originalValue = originalValue || value; + // #950 Ensure that sparse array empty slots are validated let validations = new Array(value.length); for (let idx = 0; idx < value.length; idx++) { let item = value[idx];