Skip to content

Instantly share code, notes, and snippets.

@StackTrac3
Last active January 7, 2021 23:28
Show Gist options
  • Save StackTrac3/9bb87798d3a099505c92468c0d9da77a to your computer and use it in GitHub Desktop.
Save StackTrac3/9bb87798d3a099505c92468c0d9da77a to your computer and use it in GitHub Desktop.
Keep a lookup map concise - more in comments
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) => response.input == input)
results.forEach((result) => {
if (typeof result.helper == "function") result.helper(input, callback)
else if (typeof callback == "function") callback(result.answer)
})
}
// Add a second response for test-one
responses.push({ input: "test-one", answer: "OneTwo" })
/*
The old logic here used the map like this - and it matched all responses
["test", "test-one", "test-two"].forEach((input) =>
matchResponses(input, logMessage)
)
Our quick refactor below will choose a random matching response instead of all of them
*/
const selectArray = (pool) => pool[Math.floor(Math.random() * pool.length)]
const potentialResponses = []
matchResponses("test-one", (response) => potentialResponses.push(response))
logMessage(selectArray(potentialResponses) || "default response")
@StackTrac3
Copy link
Author

The function attached to a lookup map should remain lean by either expecting processing logic in an argument, or wholly returning the matched data's object.

We can demonstrate this with a refactor of this gist

In our new case, inputs should only receive one answer. matchResponses will remain just as useful, without change, due to how we pass our logic through an argument.

We could further refactor this with the goal of being lean by passing the property name (input) to match the provided case against.

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