Skip to content

Instantly share code, notes, and snippets.

@StackTrac3
Created January 5, 2021 22:09
Show Gist options
  • Save StackTrac3/3f33f3574f929a398a05ebeeef017705 to your computer and use it in GitHub Desktop.
Save StackTrac3/3f33f3574f929a398a05ebeeef017705 to your computer and use it in GitHub Desktop.
This pattern is a dynamic and extensible alternative to multiple if-else blocks, or a switch statement
const logMessage = (message) => console.log(Date.now(), message)
const responses = [
{
input: "test-one",
answer: "One",
},
{
input: "test-two",
helper: (input, callback) => {
callback("Two helper")
},
},
]
const matchResponses = (input, callback) => {
const results = responses.filter((response) => {
return response.input == input
})
results.forEach((result) => {
if (typeof result.helper == "function") result.helper(input, callback)
else if (typeof callback == "function") callback(result.answer)
})
}
["test", "test-one", "test-two"].forEach((input) =>
matchResponses(input, logMessage)
)
@StackTrac3
Copy link
Author

See more about why we use the callback parameter on matchResponses in my related gist

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