Created
January 5, 2021 22:09
-
-
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
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
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) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See more about why we use the
callback
parameter onmatchResponses
in my related gist