Skip to content

Instantly share code, notes, and snippets.

@heymartinadams
Last active November 12, 2019 22:43
Show Gist options
  • Save heymartinadams/8c4a8057a95c73c865a2b49edc02b48b to your computer and use it in GitHub Desktop.
Save heymartinadams/8c4a8057a95c73c865a2b49edc02b48b to your computer and use it in GitHub Desktop.
The following is (in my book) an elegant approach to avoid nested ternary operations. In response to this article: https://medium.com/chrisburgin/rewriting-javascript-replacing-the-switch-statement-cfff707cf045
const name = 'Martin'
const customer = false
const human = true
// The object’s keys are irrelevant, since `Object.values` just spits out the object properties into an array.
const ternaryOps = Object.values({
1: name === 'Joe' ? 'Hi Joe!' : null,
2: customer ? 'Dear customer,' : null,
3: human ? `Hey ${name}!` : null,
default: 'To Whom It May Concern,'
})
// Find the first property that has passed the test
.find(x => x)
console.log(ternaryOps) // Spits out “Hey Martin!”
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment