Skip to content

Instantly share code, notes, and snippets.

@dsasse07
Last active Mar 8, 2021
Embed
What would you like to do?
Storing functions in Objects for Abstract invocation
// Using Conditionals
const newMessage = {type: "error", message: "You still haven't squished the bugs!"}
const generateLog = newMessage => {
if (newMessage.type === "warn" {
Log.warn(newMessage.message)
} else if (newMessage.type === "error" {
Log.error(newMessage.message)
} else if (newMessage.type === "notify" {
Log.notify(newMessage.message)
}
}
generateLog(newMessage)
// Without Conditional Statements
const newMessage = {type: "error", message: "You still haven't squished the bugs!"}
const logGenerator = {
warn: Log.warn,
notify: Log.notify,
error: Log.error
}
logGenerator[newMessage.type](newMessage.message)
// logGenerator[newMessage.type] loads the Log.error function which is then invoked
// with the argument of newMessage.message. Any of the Log functions can be called without
// any extra conditionals
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment