Repository navigation
Expand file tree
/
Copy pathvowelFlip.js
More file actions
49 lines (46 loc) · 1.43 KB
/
Copy pathvowelFlip.js
File metadata and controls
49 lines (46 loc) · 1.43 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
/**
* Write a script that will find all the vowels [a,e,i,o,u] inside any string
* and then flip the order of only the vowels. If there is an odd number of vowels
* then the one in the middle stays in the same position. Complete this task with the
* fewest number of loops and iterations as possible.
* Eg:
* cottage => cettago
* hello => holle
* sauce => seuca
* javascript => jivascrapt
*/
//solution one
/*
let process = word => {
let matches = Array.from(word).reduce((acc, curr, idx) => {
if (["a", "e", "i", "o", "u"].includes(curr)) {
acc.push(idx);
}
return acc;
}, []);
log(matches); //positions of the vowels
let len = matches.length;
let wordCopy = Array.from(word);
for (let i = 1; i <= len / 2; i++) {
let ltr = word.substring(matches[len - i], matches[len - i] + 1);
let removed = wordCopy.splice(matches[i - 1], 1, ltr);
wordCopy.splice(matches[len - i], 1, removed[0]);
word = wordCopy.join("");
}
return word;
}; */
//solution two
let process = str => {
const regex = /[aeiou]/g;
let modified = str.split('');
let vowels = str.match(regex);
modified.forEach((char, i) => {
// Handle vowels only
if (['a', 'e', 'i', 'o', 'u'].includes(char)) {
modified[i] = vowels.pop();
}
});
return modified.join('');
}
console.log(process("javascript"));
console.log(process("hello"));