repeat Builds Repeated Runs In One Call

Build rulers, indent levels, and progress bars with String.repeat: one call produces the whole run, zero repeats yield an empty string.

JavascriptCli Tooling

Code

javascriptsnippet
18 lines
// repeat 把单个字符放大成整条视觉标尺,日志里的分隔线不用手写
const ruler = '-'.repeat(40);
console.log(ruler);
console.log('STAGE 1: extract');
console.log(ruler);

// repeat 也适合生成缩进层级:层级数乘出来,不写循环
for (let depth = 0; depth < 3; depth++) {
  console.log('  '.repeat(depth) + 'node at depth ' + depth);
}

// 零次 repeat 是空字符串,边界自然成立
console.log('empty:', JSON.stringify('-'.repeat(0)));

// 与字符串拼接组合:把进度条画到指定刻度
const done = 3;
const total = 5;
console.log('[' + '#'.repeat(done) + '.'.repeat(total - done) + '] ' + done + '/' + total);

Output

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

----------------------------------------
STAGE 1: extract
----------------------------------------
node at depth 0
  node at depth 1
    node at depth 2
empty: ""
[###..] 3/5

How the snippet works

The file repeats itself only inside for (let depth = 0; depth < 3; depth++).

Top-level bindings ruler, done, total hold the demo state — nothing sits inside a function scope.

Applying it

The demo output is labeled (STAGE 1: extract, empty:), so every printed line maps back to its originating operation.

Statements that matter

const ruler = '-'.repeat(40);
const total = 5;
const done = 3;

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `ruler`, `done`, `total`.