Created
April 17, 2021 19:33
-
-
Save sayrer/b4ded0127ab96d6c02b19528a1d31a06 to your computer and use it in GitHub Desktop.
More expressive
This file contains hidden or 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 code from https://seanbarry.dev/posts/switch-true-pattern: | |
switch (true) { | |
case !isDefined(user): | |
throw new Error("User must be defined."); | |
case !isString(user.firstName): | |
throw new Error("User's first name must be a string"); | |
case !isValidEmail(user.email): | |
throw new Error("User's email address must be a valid email address"); | |
case !isValidPhoneNumber(user.number): | |
throw new Error("User's phone number must be a valid phone number"); | |
// any number of other validation cases here | |
default: | |
return user; | |
} | |
*/ | |
function isDefined(user) { | |
return true; | |
} | |
function isString(user) { | |
return true; | |
} | |
function isValidEmail(user) { | |
return true; | |
} | |
function isValidPhoneNumber(user) { | |
return true; | |
} | |
let user = {}; | |
let validation_cases = [ | |
{ | |
check: isDefined, | |
error_message: "User must be defined.", | |
}, | |
{ | |
check: isString, | |
error_message: "User's first name must be a string", | |
}, | |
{ | |
check: isValidEmail, | |
error_message: "User's email address must be a valid email address", | |
}, | |
{ | |
check: isValidPhoneNumber, | |
error_message: "User's phone number must be a valid phone number", | |
}, | |
]; | |
function validate(validation) { | |
if (validation.check(user)) { return true; } else { throw new Error(validation.error_message);}; | |
} | |
let passed = validation_cases.every(validate); | |
console.log("passed: ", passed); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment