1
+ // IMPERATIVE APPROACH
2
+
3
+ function pigLatin ( str ) {
4
+ // Convert string to lowercase
5
+ str = str . toLowerCase ( ) ;
6
+ // Initialize array of vowels
7
+ const vowels = [ "a" , "e" , "i" , "o" , "u" ] ;
8
+ // Initialize vowel index to 0
9
+ let vowelIndex = 0 ;
10
+
11
+ if ( vowels . includes ( str [ 0 ] ) ) {
12
+ // If first letter is a vowel
13
+ return str + "way" ;
14
+ } else {
15
+ // If the first letter isn't a vowel i.e is a consonant
16
+ for ( let char of str ) {
17
+ // Loop through until the first vowel is found
18
+ if ( vowels . includes ( char ) ) {
19
+ // Store the index at which the first vowel exists
20
+ vowelIndex = str . indexOf ( char ) ;
21
+ break ;
22
+ }
23
+ }
24
+ // Compose final string
25
+ return str . slice ( vowelIndex ) + str . slice ( 0 , vowelIndex ) + "ay" ;
26
+ }
27
+ }
28
+
29
+ // DECLARATIVE APPROACH
30
+ function pigLatin ( str ) {
31
+ return str
32
+ . replace ( / ^ ( [ a e i o u y ] ) ( .* ) / , '$1$2way' )
33
+ . replace ( / ^ ( [ ^ a e i o u y ] + ) ( .* ) / , '$2$1ay' ) ;
34
+ }
35
+
36
+ // FOR...OF LOOP
37
+
38
+ function pigLatin ( str ) {
39
+ const strArr = str . split ( '' )
40
+ const isVowel = / [ a , e , o , u , i ] / gi
41
+ let result = str
42
+ if ( ! strArr [ 0 ] . match ( isVowel ) ) {
43
+ for ( let i = 0 ; i < strArr . length ; i ++ ) {
44
+ if ( ! strArr [ i ] . match ( isVowel ) ) {
45
+ result = result . slice ( 1 ) + strArr [ i ]
46
+ }
47
+ else {
48
+ result = result + 'ay'
49
+ console . log ( result )
50
+ return result
51
+ }
52
+ }
53
+ } else {
54
+ return result + 'way'
55
+ }
56
+ }
0 commit comments