zeduke
zeduke

Reputation: 120

Setting ES6 default arguments to handle empty strings

Below I have an object, key-value map.

const COLORS_BY_TYPE = {
  RED: 'red',
  BLUE: 'blue',
  GREEN: 'green',
};

const getCorrectColor = ({ colorType = 'GREEN' }) => COLORS_BY_TYPE[colorType.toUpperCase()];

I have something like the following above, it works fine when I call getCorrectColor when I don't pass the correct prop it relates to. When I pass an empty string, it doesn't work as I want. How would I modify the above so that if the prop is an empty string It would resort back to the default colour.

Could anyone provide a simple example of the type of functionality I am looking for?

Upvotes: 1

Views: 3158

Answers (4)

chazsolo
chazsolo

Reputation: 8439

Another possibility is Map. Obviously this requires you to change your setup (instead of using an object literal), but Map allows you to use an empty string as a key.

const COLORS_BY_TYPE = new Map()
COLORS_BY_TYPE.set('RED', '#f00')
COLORS_BY_TYPE.set('BLUE', '#00f')
COLORS_BY_TYPE.set('GREEN', '#0f0')
COLORS_BY_TYPE.set('', COLORS_BY_TYPE.get('GREEN'))

const getCorrectColor = ({
  colorType
}) => COLORS_BY_TYPE.get(colorType.toUpperCase())

console.log(getCorrectColor({
  colorType: 'GREEN'
}))
console.log(getCorrectColor({
  colorType: ''
}))

Upvotes: 0

connexo
connexo

Reputation: 56754

I don't know why you are using a destructuring assignment, but this works for me:

const COLORS_BY_TYPE = {
RED: '#ff0000',
BLUE: '#0000ff',
GREEN: '#00ff00'
}

const getCorrectColor = (colorType = 'GREEN') =>
COLORS_BY_TYPE[colorType.toUpperCase() in COLORS_BY_TYPE ? colorType.toUpperCase() : 'GREEN'];

console.log(getCorrectColor())
console.log(getCorrectColor(''))
console.log(getCorrectColor('red'))

Upvotes: 0

Ryos
Ryos

Reputation: 396

Default parameters only get applied when the value of the parameter they stand in for is undefined. Because of this, when you pass an empty string the default value does not get applied to the parameter. However, because empty string can be coerced to false in JavaScript, you can use an OR (||) in the function body to get what you want.

This code should solve your problem:

const COLORS_BY_TYPE = {
RED: '#ffffff'
BLUE: '#ffffff'
GREEN: '#ffffff'
}

const getCorrectColor = ({colorType = 'GREEN'}) =>
COLORS_BY_TYPE[(colorType || "GREEN").toUpperCase()];

Here we are wrapping the reading of colorType in a pair of parentheses and providing a second value for when it is a value that can be coerced to false—this new value is the string "GREEN". The parentheses ensure that this is executed first, and whatever value it gives is the value whose toUpperCase() method is called.

Upvotes: 1

Bergi
Bergi

Reputation: 664444

I think you are looking for

function getCorrectColor({colorType = ''}) {
    const key = colorType.toUpperCase();
    return COLORS_BY_TYPE[key in COLORS_BY_TYPE ? key : 'GREEN'];
}

Upvotes: 2

Related Questions