skip to Main Content

I’m trying to solve this JavaScript test:

Given a string s and a number n, return a new string with the characters of s repeated n times consecutively in a circular manner. If the length of the new string is greater than 100, truncate it to a length of 100.

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


  1. 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.

    function circularRepeat1(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 circularRepeat2(s, n) {
      n = Math.min(n, 100);
      const repeatTimes = Math.floor(n / s.length);
      return s.repeat(repeatTimes) + s.slice(0, n % s.length);
    }
    
    // Should print true for all cases
    for (let n of [50, 100, 200]) {
      console.log(circularRepeat1('foobar', n) === circularRepeat2('foobar', n));
    }
    Login or Signup to reply.
  2. s.repeat(...).slice(...) is naive as large n 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 finally join the elements to produce the output string –

    function circularRepeat(s, n, maxlen = 100) {
      const a = Array(Math.max(0, Math.min(n, maxlen)))
      for (let i = 0; i < a.length; i++) a[i] = s[i % s.length]
      return a.join("")
    }
    
    console.log(circularRepeat("foobar", 2))        // length: 2
    console.log(circularRepeat("foobar", 40))       // length: 40
    console.log(circularRepeat("foobar", 600))      // length: 100
    console.log(circularRepeat("foobar", 600, 555)) // length: 555

    Here’s a recursive implementation –

    const circularRepeat = (s = "", min = 0, max = 100, z = Math.min(min, max)) =>
      z <= 0
        ? ""
        : s.length > z
          ? s.slice(0, Math.max(0, z))
          : s + circularRepeat(s, min, max, z - s.length)
    
    console.log(circularRepeat("foobar", 2))        // length: 2
    console.log(circularRepeat("foobar", 40))       // length: 40
    console.log(circularRepeat("foobar", 600))      // length: 100
    console.log(circularRepeat("foobar", 600, 555)) // length: 555
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search