-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseWords.js
More file actions
72 lines (55 loc) · 1.7 KB
/
reverseWords.js
File metadata and controls
72 lines (55 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Exemplo que eu fiz
// function reverseWords(str) {
// // reverse every word in the string
// // return the new string
// const arrayOfWords = str.split(' ');
// const reversedWords = arrayOfWords.map((word) => {
// let newWord = '';
// for (let index = word.length -1; index >= 0; index--) {
// newWord += word[index];
// }
// return newWord;
// });
// return reversedWords.join(' ');
// }
// console.log(reverseWords('this is a string of words'));
// Exemplo que me pediram para fazer sem usar split ou join
// function reverseWords(str) {
// let word = '';
// let arrWords = [];
// for (let i = 0; i < str.length; i++) {
// if (str[i] != ' ') {
// word += str[i];
// } else {
// arrWords.push(word);
// word = '';
// }
// }
// arrWords.push(word);
// let invertedWord = '';
// arrWords.forEach(word => {
// for (let i = word.length - 1; i >= 0; i--) {
// if (i === 0) {
// invertedWord += word[i] + ' ';
// } else {
// invertedWord += word[i];
// }
// }
// });
// return invertedWord;
// }
// console.log(reverseWords('Hello World again'));
// código do curso
function reverseWords(str) {
const wordsArr = str.split(' ');
const reversedWordArray = [];
wordsArr.forEach(word => {
let reversedWord = '';
for (let i = word.length - 1; i >= 0; i--) {
reversedWord += word[i];
}
reversedWordArray.push(reversedWord);
});
return reversedWordArray.join(' ');
}
console.log(reverseWords('Hello World again'));