AphrodyBun GitHub

Runtime docs · Linter · Rules

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:

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

Examples

Reported:

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

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

const left = " ".repeat(Math.floor((width - title.length) / 2));
const bar = "#".repeat(Math.min(total - done, 40));

Not reported:

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);