To exclude the trailing character, a simple solution would be:
Array.from(Array(1000 / 5),
(_, i) => (i *= 5, `${i+1} ${i+2} ${i+3} ${i+4} ${i+5}`))
.join(' * ');
We don't have to loop through 1000 times as we already know all the numbers and that there will be 200 groups of 5 numbers each. The task is to generate these groups and combine them.
However, there are some issues with this approach:
- The interval is fixed
- The separator is fixed
- What if we can't evenly divide the numbers?
For example, let's say we need to add a |
after every 4th number out of 10:
1 2 3 4 | 5 6 7 8 | 9 10
We have 2 sets of 4 numbers each and 1 set containing the last two numbers.
(I'll provide annotations to help you connect these examples with the final code below)
You can create the first two sets like this:
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 set with:
Array(10 % 4).fill(0).map((_, i) => Math.floor(10 / 4) * 4 + i + 1).join(' ')
// ^^^^^^ ^^^^^^^^^^^^^^^^^^
// tmax imax
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// nseq
//
//=> '9 10'
Then you simply 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>