Skip to content

Instantly share code, notes, and snippets.

@atomize
Created November 3, 2017 00:20
Show Gist options
  • Save atomize/734975be9c7a79ae55108f768940428c to your computer and use it in GitHub Desktop.
Save atomize/734975be9c7a79ae55108f768940428c to your computer and use it in GitHub Desktop.
Lookup tables shorthand in javascript.
// Longhand
if (type === 'aligator') {
aligatorBehavior();
}
else if (type === 'parrot') {
parrotBehavior();
}
else if (type === 'dolphin') {
dolphinBehavior();
}
else if (type === 'bulldog') {
bulldogBehavior();
} else {
throw new Error('Invalid animal ' + type);
}
// Shorthand
var types = {
aligator: aligatorBehavior,
parrot: parrotBehavior,
dolphin: dolphinBehavior,
bulldog: bulldogBehavior
};
var func = types[type];
(!func) && throw new Error('Invalid animal ' + type); func();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment