1let string = 'Plumbus'
2let count = 3
3
4string.repeat(count); // -> 'PlumbusPlumbusPlumbus'
1function repeatStringNumTimes(string, times) {
2 var repeatedString = "";
3 while (times > 0) {
4 repeatedString += string;
5 times--;
6 }
7 return repeatedString;
8}
9repeatStringNumTimes("abc", 3);
1The code below is written using ES6 syntaxes but could just as easily be written in ES5 or even less. ES6 is not a requirement to create a "mechanism to loop x times"
2
3If you don't need the iterator in the callback, this is the most simple implementation
4
5const times = x => f => {
6 if (x > 0) {
7 f()
8 times (x - 1) (f)
9 }
10}
11
12// use it
13times (3) (() => console.log('hi'))
14
15// or define intermediate functions for reuse
16let twice = times (2)
17
18// twice the power !
19twice (() => console.log('double vision'))