Skip to content

Instantly share code, notes, and snippets.

@cwood821
Created June 7, 2020 02:47
Show Gist options
  • Save cwood821/6252c383557bc2f11413d260839b9556 to your computer and use it in GitHub Desktop.
Save cwood821/6252c383557bc2f11413d260839b9556 to your computer and use it in GitHub Desktop.
Type checking locations
function isValidString(str) {
return str && typeof str === "string";
}
function isValidColor(color) {
let re = /^#[a-zA-Z0-9]{6}$/;
return isValidString(color) && re.test(color);
}
const TYPE_MAP = {
"string": isValidString,
"color": isValidColor
};
function validate(item, schema, ctx = {}) {
let valid = true;
for (let key of Object.keys(item)) {
let type = schema[key];
let isValid = TYPE_MAP[type];
if (typeof isValid === "function") {
if (!isValid(item[key])) {
console.error(`Item failed validation at key '${key}' with value ${item[key]}, should be type ${type}`, ctx);
valid = false;
}
} else {
console.error(`Non-existent type given for item with at key '${key}'`, ctx);
}
}
return valid;
}
const LOCATION_SCHEMA = {
"Name of Organization": "string",
"color": "color"
}
let rawLocations = [
{
"Name of Organization": "",
"color": "#ffffff"
},
{
"Name of Organization": "An organization",
"color": "#red"
}
]
let validLocations = rawLocations.filter((loc, i) => validate(loc, LOCATION_SCHEMA, { sheetRow: i + 1 }));
@cwood821
Copy link
Author

cwood821 commented Jun 7, 2020

Running this should output:

Item failed validation at key 'Name of Organization' with value , should be type string { sheetRow: 1 }
Item failed validation at key 'color' with value #red, should be type color { sheetRow: 2 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment