Assuming you don't want the trailing character, you could simply do:
Array.from(Array(1000 / 5),
(_, i) => (i *= 5, `${i+1} ${i+2} ${i+3} ${i+4} ${i+5}`))
.join(' * ');
We don't need to iterate 1000 times: we know all the numbers already and we know we'll have 200 groups of 5 numbers each. We just need to produce those groups and join them up together.
But there are many issues with this:
- The interval is hardcoded
- The separator is hardcoded
- What if we can't split evenly the numbers?
Let say we need to insert a |
after every 4th numbers of 10 numbers:
1 2 3 4 | 5 6 7 8 | 9 10
We have 2 groups of 4 numbers each and 1 group with the last two numbers.
(I am going to annotate these examples so you can hopefully connect them with the full example below)
The first two groups can be produced as follow:
Array.from(Array(Math.floor(10 / 4)), (_, i) => (i*=4, [i+1, i+2, i+3, i+4].join(' ')))
// ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^
// imax tmpl
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// nseq
//
//=> ['1 2 3 4', '5 6 7 8']
The last group with:
Array(10 % 4).fill(0).map((_, i) => Math.floor(10 / 4) * 4 + i + 1).join(' ')
// ^^^^^^ ^^^^^^^^^^^^^^^^^^
// tmax imax
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// nseq
//
//=> '9 10'
Then you basically do:
['1 2 3 4', '5 6 7 8'].concat('9 10').join(' | ')
//=> '1 2 3 4 | 5 6 7 8 | 9 10'
Demo
console.log("sprintnums(10, 7, '|') -> " + sprintnums(10, 7, '|'));
console.log("sprintnums(10, 4, '|') -> " + sprintnums(10, 4, '|'));
console.log("sprintnums(10, 2, '|') -> " + sprintnums(10, 2, '|'));
console.log("sprintnums(10, 1, '|') -> " + sprintnums(10, 1, '|'));
console.log(`
In your case:
${sprintnums(1000, 5, '*')}
`);
<script>
function sprintnums(n, x, c) {
const tmpl = Array(x).fill(0);
const nseq = (arr, mul) => arr.map((_, i) => mul * x + i + 1).join(' ');
const imax = Math.floor(n / x);
const tmax = n % x;
const init = Array.from(Array(imax), (_, mul) => nseq(tmpl, mul));
const tail = tmax ? nseq(Array(tmax).fill(0), imax) : [];
return init.concat(tail).join(` ${c} `);
}
</script>