xxxxxxxxxx
function doubleString(string) {
return string.repeat(2);
}
// Should return 'echoecho'
console.log("doubleString('echo') returns: " + doubleString("echo"));
xxxxxxxxxx
// Repeat a String Repeat a String
// Repeat a given string str (first argument) for num times (second argument).
// Return an empty string if num is not a positive number. For the purpose of this challenge, do not use the built-in .repeat() method.
function repeatStringNumTimes(str, num) {
if (num < 0) return '';
let result = '';
for (let i = 0; i <= num - 1; i++) {
result += str;
}
return result;
}
repeatStringNumTimes('abc', 3);
// OR
function repeatStringNumTimes(str, num) {
var accumulatedStr = '';
while (num > 0) {
accumulatedStr += str;
num--;
}
return accumulatedStr;
}
// OR
function repeatStringNumTimes(str, num) {
if (num < 1) {
return '';
} else {
return str + repeatStringNumTimes(str, num - 1);
}
}
// OR
// my favourite
function repeatStringNumTimes(str, num) {
return num > 0 ? str + repeatStringNumTimes(str, num - 1) : '';
}
xxxxxxxxxx
let labels = [];
repeat(5, i => {
labels.push(`Unit ${i + 1}`);
});
console.log(labels);
// → ["Unit 1", "Unit 2", "Unit 3", "Unit 4", "Unit 5"]