Skip to content

Commit

Permalink
feat: pull validation into separate module
Browse files Browse the repository at this point in the history
  • Loading branch information
ericdeansanchez committed Nov 18, 2020
1 parent bb4b36d commit a113fea
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/validators.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {
MIN_SRCSET_WIDTH,
MAX_SRCSET_WIDTH,
DEFAULT_SRCSET_WIDTH_TOLERANCE
} from './constants.js';

export function validateAndDestructureOptions(options) {
if (options.widthTolerance !== undefined) {
validateWidthTolerance(options.widthTolerance);
var widthTolerance = options.widthTolerance;
} else {
var widthTolerance = DEFAULT_SRCSET_WIDTH_TOLERANCE;
}

var minWidth = options.minWidth === undefined ? MIN_SRCSET_WIDTH : options.minWidth;
var maxWidth = options.maxWidth === undefined ? MAX_SRCSET_WIDTH : options.maxWidth;

// Validate the range unless we're using defaults for both
if (minWidth != MIN_SRCSET_WIDTH || maxWidth != MAX_SRCSET_WIDTH) {
validateRange(minWidth, maxWidth);
}

return [widthTolerance, minWidth, maxWidth];
}

export function validateRange(min, max) {
if (!(Number.isInteger(min) && Number.isInteger(max)) || (min <= 0 || max <= 0) || (min > max)) {
throw new Error('The min and max srcset widths can only be passed positive Number values');
}
}

export function validateWidthTolerance(widthTolerance) {
if (typeof widthTolerance != 'number' || widthTolerance <= 0) {
throw new Error('The srcset widthTolerance argument can only be passed a positive scalar number');
}
}

export function validateWidths(customWidths) {
if (!Array.isArray(customWidths) || !customWidths.length) {
throw new Error('The widths argument can only be passed a valid non-empty array of integers');
} else {
var allPositiveIntegers = customWidths.every(
function (width) {
return Number.isInteger(width) && width > 0
}
);
if (!allPositiveIntegers) {
throw new Error('A custom widths argument can only contain positive integer values');
}
}
}

export function validateVariableQuality(disableVariableQuality) {
if (typeof disableVariableQuality != 'boolean') {
throw new Error('The disableVariableQuality argument can only be passed a Boolean value');
}
}

0 comments on commit a113fea

Please sign in to comment.