|
| 1 | +# 0006 Repate a String Num times ( L-I ) |
| 2 | +## Problem |
| 3 | + |
| 4 | +repeat a given string `str` for `num` of times, and return empty in case the num is zero or negative number, and without using `.repeat()` method. |
| 5 | + |
| 6 | +## Test Cases |
| 7 | + |
| 8 | +- str = "A" and num = 5, the function should return "AAAAA". |
| 9 | +- str = "A" and num = 0, the function should return "". |
| 10 | +- str = "A" and num = 2, the function should return "AA". |
| 11 | +- str = "A" and num = -1, the function should return "". |
| 12 | +## Solution |
| 13 | + |
| 14 | +```javascript |
| 15 | +const repeatStringNumTimes = (str, num) => { |
| 16 | + if (num < 1) { |
| 17 | + return ""; |
| 18 | + } |
| 19 | + // here I used recursion technique to solve the problem |
| 20 | + return str + repeatStringNumTimes(str, num - 1); |
| 21 | +}; |
| 22 | + |
| 23 | +console.log(repeatStringNumTimes("abc", 3)); |
| 24 | +``` |
| 25 | + |
| 26 | +## How it works |
| 27 | + |
| 28 | +- The function takes two parameters. |
| 29 | +- The first is a string, and the second a integer number. |
| 30 | +- If the the second parameter is number and positive, it will return the string * number of times. |
| 31 | + |
| 32 | +## References |
| 33 | + |
| 34 | +- [Khan Academy](https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/recursion) |
| 35 | +- [FreeCodeCamp](https://www.freecodecamp.org/news/three-ways-to-repeat-a-string-in-javascript-2a9053b93a2d/) |
| 36 | + |
| 37 | +## Problem Added By |
| 38 | +- [GitHub](https://github.com/ibr5500) |
| 39 | +- [LinkedIn](https://www.linkedin.com/in/ibrahim-ahmat/) |
| 40 | +- [Twitter](https://twitter.com/ibr_ahmat) |
| 41 | + |
| 42 | +## Contributing |
| 43 | +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. |
| 44 | + |
| 45 | +Please make sure to update tests as appropriate. |
0 commit comments