I have a function that formats currency:
export const formatDollar = (dollar) => {
const format = function moneyFormat(val, sign = '$ ') {
const pieces = parseFloat(val).toFixed(2).split('');
let ii = pieces.length - 3;
while ((ii -= 3) > 0) {
pieces.splice(ii, 0, ',');
}
return sign + pieces.join('');
};
return format(dollar);
};
This part is causing an ESLint error:
while ((ii -= 3) > 0) {
pieces.splice(ii, 0, ',');
}
error Unexpected assignment within a 'while' statement no-cond-assign
How should i write this statement so that ESLint check passes?
Expression ii -= 3
is equivalent to ii = ii - 3
and can be replaced with ii - 3 > 0
. However, since in this case it doesn't modify variable ii
anymore. You need to decrement it explicitly in loop. So you could rewrite it like this:
while (ii > 3) { // or ii - 3 > 0
ii = ii - 3;
pieces.splice(ii, 0, ',');
}
Couple of tests:
const formatDollar = (dollar) => {
const format = function moneyFormat(val, sign = '$ ') {
const pieces = parseFloat(val).toFixed(2).split('');
let ii = pieces.length - 3;
while (ii > 3) {
ii = ii - 3
pieces.splice(ii, 0, ',');
}
return sign + pieces.join('');
};
return format(dollar);
};
console.log(formatDollar(12345678))
console.log(formatDollar(12345))
console.log(formatDollar(12))
console.log(formatDollar(.12))