Reputation: 89
Is there a way this if statement can be simplified. I find I am in this senario alot and want to make it cleaner.
if (item === 'christie' || item === 'chris') {
return 'christine';
}
if (item === 'maddy' || item === 'madison') {
return 'madeline';
}
return '';
I created an example for the sake of the question but is there a simpler way?
Upvotes: 0
Views: 85
Reputation: 3371
Depending on the use case it can be simpler to do something like the following:
const name_map = {
'christie': 'christine',
'chris': 'christine',
'maddy': 'madeline',
'madison': 'madeline',
};
const map_name = (name) => name_map[name] ? name_map[name] : name;
console.log('christie', map_name('christie'));
console.log('christine', map_name('christine'));
console.log('maddy', map_name('maddy'));
If you wanted to specify the name relationship the other way around you could probably do something like:
const name_map = {
'christine': ['christie', 'chris'],
'madeline': ['maddy', 'madison'],
};
const flip = (obj) => Object.entries(obj)
.reduce(
(acc1, [name, alts]) => alts.reduce(
(acc2, alt) => ({ ...acc2, [alt]: name }),
acc1
),
{}
)
const flipped_name_map = flip(name_map);
const map_name = (name) => flipped_name_map[name] ? flipped_name_map[name] : name;
console.log('christie', map_name('christie'));
console.log('christine', map_name('christine'));
console.log('maddy', map_name('maddy'));
console.log('madison', map_name('madison'));
Upvotes: 1
Reputation: 655
You can use a switch statement
function switch_names(item) {
switch (item) {
case "christie":
case "chris":
return "christine";
case "maddy":
case "madison":
return "madeline";
default:
return "";
}
}
const name=switch_names("chris")
console.log(name)
Upvotes: 2
Reputation: 757
A bit longer but easier to quickly grasp what's going on. According to me atleast.
switch(item) {
case 'christie':
case 'chris':
return 'christine';
case 'maddy':
case 'madison':
return 'madeline';
default:
return '';
}
Here's another option using includes
if(['christie','chris'].includes(item)) {
return 'christine';
}
if(['maddy','madison'].includes(item)) {
return 'madeline';
}
return '';
Upvotes: 3
Reputation: 1218
One option assuming the names you provided are the only name options and the returned value is according to the prefix.
return item.startsWith('chr') ? 'christine' : item.startsWith('mad') ? 'madeline' : '';
If you want to stay with if
you can use:
if (item.startsWith('chr')) return 'christine';
if (item.startsWith('mad')) return 'madeline';
return '';
Upvotes: 2
Reputation: 88
if (item === 'christie' || item === 'chris' ||item === 'maddy' || item === 'madison')
{
return item;
}
return '';
Your post was very unclear, what do you want exactly?
Upvotes: 0