Ad

How To Repeat The 123 1231 Till The Length Target

how to print the number in str and repeat it till the length target, example:

if we have num = 4 and the str target we print is 123,

so the newStr = should be 1231 and if the num = 6 the newStr = 123123

the newStr.length should be like the num

function repeatIt(num) {
  var arr = [],
    markIt = true,
    add = true,
    hastag = true;
  while (arr.length < num) {
    var pushThis = "";
    if (markIt) {
      pushThis = "!";
       markIt = false;
    } else if (add) {
      pushThis = "@";
       add = false;
       hastag = true;
    } else if (hastag) {
      pushThis = "#";
       hastag = false;
       markIt = true;
       add = true;
    };
    arr.push(pushThis)
  };
  return num > 0 ? arr : "invalid input"
};

console.log(repeatIt(3))
// output : ['!','@','#'] 123 

console.log(repeatIt(6));
// output : ['!','@','#','!','@','#'] 123 123

console.log(repeatIt(4))
// output : ['!','@','#','!'] 123 1

console.log(repeatIt(0)) // invalid input

the above is my example and that is my code, I check and change the parameter, it matches with the output I want, but my codes seem not clean and too long, is there any way to write the code better for that example above, ??

Ad

Answer

You might use an array of characters, then use Array.from to construct the array, and check i % chars.length to get the correct character:

function repeatIt(length) {
  if (length === 0) return "invalid input";
  const chars = ['!', '@', '#'];
  return Array.from(
    { length },
    (_, i) => chars[i % chars.length]
  )
}

console.log(repeatIt(3))
// output : ['!','@','#'] 123 

console.log(repeatIt(6));
// output : ['!','@','#','!','@','#'] 123 123

console.log(repeatIt(4))
// output : ['!','@','#','!'] 123 1

console.log(repeatIt(0)) // invalid input

Ad
source: stackoverflow.com
Ad