Skip to content

Instantly share code, notes, and snippets.

@Quacky2200
Created January 2, 2020 06:58
Show Gist options
  • Save Quacky2200/7863d4ec01b5f368a0a46ec02188ee93 to your computer and use it in GitHub Desktop.
Save Quacky2200/7863d4ec01b5f368a0a46ec02188ee93 to your computer and use it in GitHub Desktop.
Test JavaScript file to test measurements are valid
/**
* This function returns whether the given values are valid measurements.
*
* @param string|string[] inputArray List or string of measures
* @param string|string[] validUnits List or string of valid units
* @param mixed opts Options
* @return boolean Whether measure(s) is valid
*/
function checkValidUnits(inputArray, validUnits, opts) {
opts = opts || {};
// opts.unitFormat;
opts.caseSensitivity = !!opts.caseSensitivity || false;
opts.returnType = opts.returnType || 'truthy' // truthy/data/both
opts.useReference = !!opts.useReference || true;
if (typeof(inputArray) == 'object' && inputArray.constructor.name !== 'Array') {
// This is not an array, and we cannot
// understand it at this point.
return false;
}
var isArray = typeof(inputArray) !== 'string';
if (!opts.useReference && isArray) {
inputArray = Object.assign({}, inputArray);
}
if (!isArray) {
inputArray = [inputArray];
}
if (typeof(validUnits) == 'string') {
validUnits = [validUnits];
} else if (typeof(validUnits) == 'object' && validUnits.constructor.name !== 'Array') {
// This is not an array, and we cannot
// understand it at this point.
return false;
}
var unitregex = validUnits.join('|');
var dp = '(?:\\.\\d+)'; // decimal point
var regex = new RegExp('^((?:\\d+' + dp + '?)|' + dp + ')(' + unitregex + ')$', opts.caseSensitivity ? '' : 'i');
var valid = true;
for(var input in inputArray) {
var value = inputArray[input];
if (match = regex.exec(value)) {
value = {
units: match[1],
unit: match[2]
}
} else {
valid = false;
value = {
error: 'Invalid measurement/unit',
original: value,
units: null,
unit: null
}
}
if (typeof(opts.unitFormat) == 'function') {
value = opts.unitFormat(value);
}
inputArray[input] = value
}
if (opts.returnType == 'both') {
return {
valid: valid,
data: inputArray
};
} else if (opts.returnType == 'data') {
return inputArray;
} else if (opts.returnType == 'truthy') {
return valid;
} else {
throw new Error('Invalid returnType');
}
}
function checkValidCSSMeasurement(input) {
return checkValidUnits(input, [
"cm",
"mm",
"in",
"px",
"pt",
"pc",
"em",
"ex",
"ch",
"rem",
"vw",
"vh",
"vmin",
"vmax",
"%"
]);
}
function checkValidStorageMeasurement(input) {
return checkValidUnits(input, [
"EB",
"PB",
"TB",
"GB",
"MB",
"KB",
"B"
]);
}
function checkValidWeightMeasurement(input) {
// 1st 2lbs will have to be split...
return checkValidUnits(input, [
'lbs?',
'kgs?',
'st',
'ounces?',
'tons?',
'g',
'mg', // miligrams (mg) or megagrams (Mg - ton)
'μg', // micrograms
' ?grams?',
' ?stone',
' ?pounds?',
' ?kilograms?',
' ?milligrams?',
' ?micrograms?',
], {
unitFormat: function(v) {
v.unit = v.toLowerCase().replace(' ', '');
}
});
}
// etc...
///////////
// Tests //
///////////
function check(bool) {
return bool ? '(passed)' : '(failed)';
}
// Check general
var units_a = ['1px', '2.7em', '0.1pc', '10vw'];
console.log('Checking A:', units_a, '-', check(checkValidCSSMeasurement(units_a)));
// Check decimals
var units_b = ['0.1px', '.55em'];
console.log('Checking B:', units_b, '-', check(checkValidCSSMeasurement(units_b)));
// Check case
var units_c = ['0.1Px', '.55PX'];
console.log('Checking C:', units_c, '-', check(checkValidCSSMeasurement(units_c)));
// Check type 1
var units_d = '1px';
console.log('Checking D:', units_d, '-', check(checkValidCSSMeasurement(units_d)));
// Check type 2 (expect error)
var units_e = {/* invalid */};
console.log('Checking E (fails):', units_e, '-', check(checkValidCSSMeasurement(units_e) == false));
// Check errors
var units_f = ['1NM'];
console.log('Checking F (fails):', units_f, '-', check(checkValidCSSMeasurement(units_f) == false));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment