Created
June 7, 2020 02:47
-
-
Save cwood821/6252c383557bc2f11413d260839b9556 to your computer and use it in GitHub Desktop.
Type checking locations
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
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 })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running this should output: