Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:
If the first character in string is in the set , then return A. If the first character in string is in the set , then return B. If the first character in string is in the set , then return C. If the first character in string is in the set , then return D. Hint: You can get the letter at some index in using the syntax s[i] or s.charAt(i).
function getLetter(s) { let letter; //letter=s.charAt(0) const set1= new Set(['a','e','i','o','u']); const set2=new Set(['b','c','d','f','g']); const set3=new Set(['h','j','k','l','m']); const set4=new Set(['n','p','q','r','s','t','v','w','x','y','z']); // Write your code here switch(s.charAt(0)){ case 1: if(set1.has(s.charAt(0))) letter=A; break; case 2: if(set2.has(s.charAt(0))) letter=B; break; case 3: if(set3.has(s.charAt(0))) letter=C; break; case 4: if(set4.has(s.charAt(0))) letter=D; break; } return letter; }
Wanted to know what is wrong in this code, I am getting undefined in the result.
Advertisement
Answer
You could check against the set with a boolean value.
function getLetter(s) { let letter; const set1 = new Set(['a', 'e', 'i', 'o', 'u']); const set2 = new Set(['b', 'c', 'd', 'f', 'g']); const set3 = new Set(['h', 'j', 'k', 'l', 'm']); const set4 = new Set(['n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']); // Write your code here switch (true) { case set1.has(s[0]): letter = 'A'; break; case set2.has(s[0]): letter = 'B'; break; case set3.has(s[0]): letter = 'C'; break; case set4.has(s[0]): letter = 'D'; break; } return letter; } console.log(getLetter('e')); console.log(getLetter('b')); console.log(getLetter('k')); console.log(getLetter('s'));