-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: pull validation into separate module
- Loading branch information
1 parent
bb4b36d
commit a113fea
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | ||
} | ||
} |