Skip to content

Commit

Permalink
fix: handle sparse array positions as undefined (#950)
Browse files Browse the repository at this point in the history
* Handle sparse array positions as undefined

* Update src/array.js

Co-authored-by: Jason Quense <monastic.panic@gmail.com>
  • Loading branch information
VanTanev and jquense authored Jun 26, 2020
1 parent 27b287b commit 4e77348
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,11 @@ inherits(ArraySchema, MixedSchema, {

originalValue = originalValue || value;

let validations = value.map((item, idx) => {
var path = makePath`${options.path}[${idx}]`;
// #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];
let path = makePath`${options.path}[${idx}]`;

// object._validate note for isStrict explanation
var innerOptions = {
Expand All @@ -97,10 +100,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 4e77348

Please sign in to comment.