repeat Duplicates Strings, Rejecting Bad Counts

Duplicate strings with repeat for indentation and separator lines: zero returns the empty string, while negative or infinite counts raise RangeError.

JavascriptCli Tooling

Code

javascriptsnippet
28 lines
// repeat 复制字符串 n 次
console.log("ab".repeat(3));
console.log("-".repeat(10));

// 0 次返回空串,负数或 Infinity 抛 RangeError
console.log("x".repeat(0) === "");

try {
  "x".repeat(-1);
} catch (e) {
  console.log("negative:", e.name);
}

try {
  "x".repeat(Infinity);
} catch (e) {
  console.log("infinity:", e.name);
}

// 实际用途:缩进与分隔线
function indent(level, text) {
  return "  ".repeat(level) + text;
}
console.log(indent(2, "nested item"));

// 构建固定宽度分隔符
const width = 20;
console.log("+".repeat(width + 2));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ababab
----------
true
negative: RangeError
infinity: RangeError
    nested item
++++++++++++++++++++++

How the snippet works

Everything happens inside the function indent.

Caveats

  • Everything it calls is documented as part of the language core.

Using it

Entry signature: function indent(level, text)

The run prints ab, negative:, infinity: — each prefix names the step that produced it.

Key statements

return "  ".repeat(level) + text;

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `indent` at load time.