'How to spread/optimize this javascript code
I have this function:
function(x, callBack) {
const c = x?.properties.color || red
const h = x?.properties.high || 1
const a = x?.properties.alt || 5
const la = x?.properties.lat || 4
const lo = x?.properties.lon || 3
const w = x?.properties.width ||| 2
callBack(c, h, a, la, lo, w)
}
How can I reduce the number of lines using this operator { color } = x?.properties ?. My problem is the default values.
Solution 1:[1]
Since all the values are inside properties, we can use the spread syntax with the fallback values.
The only 'change' happening is that instead of the short variable names, you'll need to use the original keys
function fooBar(x, callBack) {
const {
color = 'red',
high = 1,
alt = 5
} = x?.properties || {};
callBack(color, high, alt);
}
fooBar({ properties: { color: 'orange' } }, (...all) => console.log('#1', all));
fooBar({ properties: undefined }, (...all) => console.log('#2', all));
Note: As @Felix mentioned, keep in mind that the logical OR (||) has some other behaviour than the fallback =.
Solution 2:[2]
You can handle it like this, but when you check of nullish operator it might return undefined, you have to take care of that in advance.
function (x, callBack) {
const properties = x?.properties || {};
const {
color = 'red',
high = 1,
alt = 5,
lat = 4,
lon = 3,
width = 2
} = properties;
callBack(color, high, alt, lat, lon, width);
}
Solution 3:[3]
You can go all the way using object destructuring:
function f({properties: {color: c = 'red', high: h = 1, alt: a = 5, lat: la = 4, lon: lo = 3, width: w = 2} = {}} = {}, callBack) {
callBack(c, h, a, la, lo, w);
}
const callbackFunction = function() {
console.log(...arguments);
}
f(undefined, callbackFunction)
f({ properties: {} }, callbackFunction)
f({ properties: { color: 'test', alt: 4 } }, callbackFunction)
Or, if you don't need to rename all the variables, simply use
function f({properties: {color = 'red', high = 1, alt = 5, lat = 4, lon = 3, width = 2} = {}} = {}, callBack) {
callBack(color, high, alt, lat, lon, width);
}
I've used = {} twice (once to set the default value of the properties property to an empty object in case it is absent and once to set the default value of the first parameter as a whole to an empty object in case it is completely absent/undefined) so that it wont throw any errors in those cases. This is slightly different from your code, where it will throw an error if an object is passed, but the properties property is missing.
Another small difference is that || will use the right-hand operand for any falsy value, whereas the default value in object destructuring is only used when its value is undefined.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rahul Sharma |
| Solution 3 |
