# 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.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

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

{/* End of the generated section. */}

## Examples

Reported:

{/* bad */}
```js
function pad(label, width) {
  return label + " ".repeat(width - label.length);
}
```

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

{/* bad {"count": 2} */}
```js
const left = " ".repeat(Math.floor((width - title.length) / 2));
const bar = "#".repeat(Math.min(total - done, 40));
```

Not reported:

{/* good */}
```js
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:

{/* good */}
```js
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:

{/* good */}
```js
const missing = width - label.length;
const padding = " ".repeat(missing);
```
