bun/no-negative-repeat-count

Disallow a repeat() count that comes from a subtraction and can be negative

has suggestions

" ".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:

bunfig.toml
[lint.rules]
"bun/no-negative-repeat-count" = "error" # or "warn"

Examples#

example.js1 problem
function pad(label, width) {
  return label + " ".repeat(width - label.length);
}

Rounding doesn't help, and neither does an upper bound:

example.js2 problems
const left = " ".repeat(Math.floor((width - title.length) / 2));
const bar = "#".repeat(Math.min(total - done, 40));
example.jsNo problems
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:

example.jsNo problems
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:

example.jsNo problems
const missing = width - label.length;
const padding = " ".repeat(missing);