I’m trying to solve this JavaScript test:
Given a string
s
and a numbern
, return a new string with the characters ofs
repeated n times consecutively in a circular manner. If the length of the new string is greater than100
, truncate it to a length of100
.
So far, I’ve tried these options, but they all fail.
function circularRepeat(s, n) {
n = Math.min(n, 100); // Ensure n doesn't exceed 100
let result = "";
for (let i = 0; i < n; i++) {
result += s[i % s.length]; // Use modulo to select characters circularly
}
return result;
}
function circularRepeat(s, n) {
return n > 100 ? s.repeat(100) : s.repeat(n);
}
What’s wrong here? how can it be solved?
2
Answers
You will need to calculate:
n / len(s)
to determine how many times to repeat. After that, you just strap on the remainder substring at the end.s.repeat(...).slice(...)
is naive as largen
produce large strings, where all but the first 100 chars are thrown. Allocate an array with only the number of elements you will need, then finallyjoin
the elements to produce the output string –Here’s a recursive implementation –