Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle sparse array positions as undefined V2 #950

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
jquense marked this conversation as resolved.
Show resolved Hide resolved
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);
});
});