Introduction
In this coding challenge, we are given a function with two arguments: a string (str = 'abc') and a number (num = 3) . Our task is to solve this challenge and produce the string abc repeated as many times as the number indicates (e.g., 'abcabcabc'). It is strictly prohibited to use the built-in method repeat() (commonly available in most programming languages) because using built-in methods would defeat the purpose of the coding challenge. It is unacceptable to use built-in methods during coding interviews. This challenge can be solved in any programming language, but in this article, we will use JavaScript to solve it. If you have any doubts about this, don't worry; they will be cleared once we go a bit further into it. Let’s start coding
Remember, there are countless ways to solve any coding challenge or problem in every programming language, I am going to show you one and simple.
Solution:
function repeatStringNumTimes(str, num) {
let finalStr = "";
for(let i = 0; i < num; i++) {
finalStr += str;
}
return finalStr;
}
console.log(repeatStringNumTimes("abc", 3));
// output: abcabcabc
Breaking Up Solution:
Let's break this down for clarity!
As you can see, repeatStringNumTimes is a function with two arguments, str and num. It is a normal function. Hopefully, you have prior knowledge about functions, as I am not going into depth about them for now. As we already know, str is a variable where our Words will be stored, while num is a variable where our Number will be stored.
Great! We have explored the function, and now it's time to solve it. First, we need to declare a new variable where we will later assign our string after successfully repeating it. I have declared finalStr as a variable and left it empty for now. You can see it below:
let finalStr = '';
Now, we are not far from starting the operation to repeat our string. We use a for loop for this purpose. Within the loop, we set i = 0 to start from 0 and i < num to stop before num (when num = 3, our loop will start from 0 and stop on 2, as the length is 3, counting 0, 1, 2). We can start our loop with i = 1 and stop on i <= num, but I prefer the basic structure of starting the loop with i = 0.
As you can see, the loop will take 3 steps (0, 1, 2), so our str will be abcabcabc from this abc. Finally, we will assign our repeated str to finalStr using the += sign. It's important to note that without using the + operator, the current state of str ('abcabcabc') will not be assigned; instead, we will get the previous state of str ('abc').
At the end, we return finalStr since it is essential for the final output in every function.