bun/no-negative-repeat-count
Disallow a repeat() count that comes from a subtraction and can be negative
" ".repeat(width - label.length) works until a label is longer than width. Then the count is negative and repeat() throws a RangeError. Tests with short labels don't catch it.
The rule reports a count that contains a subtraction or a negation, unless Math.max() with a literal of zero or more, as in Math.max(0, n), keeps it from going negative.
The rule suggests wrapping the count in Math.max(0, ...). --fix-suggestions applies that.
Configure#
Off by default. To turn it on:
[lint.rules]
"bun/no-negative-repeat-count" = "error" # or "warn"Examples#
function pad(label, width) {
return label + " ".repeat(width - label.lengthrepeat() throws a RangeError if this count is negative. Give it a lower bound.);
}Rounding doesn't help, and neither does an upper bound:
const left = " ".repeat(Math.floor((width - title.length) / 2)repeat() throws a RangeError if this count is negative. Give it a lower bound.);
const bar = "#".repeat(Math.min(total - done, 40)repeat() throws a RangeError if this count is negative. Give it a lower bound.);function pad(label, width) {
return label + " ".repeat(Math.max(0, width - label.length));
}For padding, use padEnd() or padStart(). If the string is already long enough, they return it unchanged:
function pad(label, width) {
return label.padEnd(width);
}The rule only looks at the expression in the call. It doesn't follow a count that's computed earlier:
const missing = width - label.length;
const padding = " ".repeat(missing);