The rule prefer-const with the option {"destructuring": "any"} will report an error on unit is never reassigned. Use 'const' instead
function foo(value) {
let [, v, unit] = value.toLowerCase().match(/(\d+)([a-z]*)/) || [];
if (unit === 'rpx') {
v *= 1.5;
}
return v ? parseInt(v, 10) : 0;
}
If I modify the code for fixing this error, the code will become not elegant.
function foo2(value) {
const result = value.toLowerCase().match(/(\d+)([a-z]*)/) || [];
let [, v] = result;
const [, , unit] = result;
if (unit === 'rpx') {
v *= 1.5;
}
return v ? parseInt(v, 10) : 0;
}
Is there any better suggestion?
function foo(value) {
const [, v, unit] = value.toLowerCase().match(/(\d+)([a-z]*)/) || [];
const parsed = parseInt(v, 10);
if (!parsed) {
return 0;
}
return unit === 'rpx' ? parsed * 1.5 : parsed;
}
Note how I鈥檝e also fixed the bug of multiplying by 1.5 on an unparsed string, as well as a string that is truthy but parses to NaN will now return 0 :-)
@ljharb Thanks for your bugfix. 馃ぃ
If properties are destructuring from an Object, you prefer setting them all const first, and reassign the some of the properties to another variables, or just divide them into const and let from the beginning?
function foo(obj) {
const { a, b, c, d, e, f } = obj;
const _d = bar(a, b, c, d);
const _e = bar(a, b, c, e);
const _f = bar(a, b, c, f);
return { ...obj, d: _d, e: _e, f: _f };
}
function foo2(obj) {
const { a, b, c } = obj;
let { d, e, f } = obj;
d = bar(a, b, c, d);
e = bar(a, b, c, e);
f = bar(a, b, c, f);
return { ...obj, d, e, f };
}
I think the second one is better, because I don't need to think another name for the properties, and assemble a new Object very quickly by the property shorthand.
I mean, ideally you don't need let at all - but yes, I'd say the second one is better in that case.
Can also avoid the interim variables and assign directly to the object properties.
function foo2(obj) {
const { a, b, c, d, e, f } = obj;
return {
...obj,
d: bar(a, b, c, d),
e: bar(a, b, c, e),
f: bar(a, b, c, f),
};
}
Most helpful comment
Can also avoid the interim variables and assign directly to the object properties.