'To finish the function scrollingText(word)
I am writing a program where I want the following result:
[ 'ROBOT', 'OBOTR', 'BOTRO', 'OTROB', 'TROBO' ]
Now I have:
[ 'robotr', 'obotr', 'botr', 'otr', 'tr' ]
Where am I going wrong? Here is my code:
function scrollingText(word) {
word = word.toUpperCase();
let arr = [];
for (let i = 0; i < word.length; i++) {
arr.push(word[i] + word.slice(i + 1) + word[0]);
}
return arr;
}
console.log(scrollingText('robot'));
Solution 1:[1]
You need to update word in each iteration, and not merely slice the same word repeatedly. Here is my snippet:
function scrollingText(word) {
let arr = [word.toUpperCase()]; // storing original word
let wordLength = word.length;
for (let i = 0; i < wordLength - 1; i++) { // iterating for one less than the string length, in this case, from 0 to 3
word = word.slice(1) + word[0] // <<-- update word in every iteration
arr.push(word.toUpperCase());
}
return arr;
}
console.log(scrollingText('robot'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wai Ha Lee |
