Skip to content

Commit

Permalink
Handle sparse array positions as undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
VanTanev committed Jun 25, 2020
1 parent 27b287b commit dc9f4a0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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,
Expand Down
16 changes: 16 additions & 0 deletions test/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

0 comments on commit dc9f4a0

Please sign in to comment.