convert a string to a new string where each character in the new string is “(” if that character appears only once in the original string, or “)” if that character appears more than once. can’t find where i make a mistake
“din” => “(((“
“recede” => “()()()”
“Success” => “)())())”
“(( @” => “))((“
const duplicateEncode = (word) => { let newString = ''; [...word.toLowerCase()].filter((e, i) => { if (word.indexOf(e) !== i) { newString += ')'; } else if (word.lastIndexOf(e) !== i ) { newString += ')'; } else newString += '('; }); return newString; }
Advertisement
Answer
You issue seems to be that you’re using .indexOf()
and .lastIndexOf()
on word
, which contains both uppercase and lowercase letters, but e
will always be the lowercase character from your input, which results in .indexOf()
and .lastIndexOf()
not being able to find the letter when it’s upercase. Instead, store the lowercase version of your input in a new variable and use that when you call .indexOf()
/.lastIndexOf()
:
const duplicateEncode = (word) => { let newString = ''; const lowerWord = word.toLowerCase(); [...lowerWord].forEach((e, i) => { if (lowerWord.indexOf(e) !== i) { newString += ')'; } else if (lowerWord.lastIndexOf(e) !== i ) { newString += ')'; } else newString += '('; }); return newString; } console.log(duplicateEncode("din")); // "(((" console.log(duplicateEncode("recede")); // "()()()" console.log(duplicateEncode("Success")); // ")())())" console.log(duplicateEncode("(( @")); // "))((" console.log(duplicateEncode("nGnnI)nPne@uwJ")); // ")())(()()((((("
You should also use .forEach()
instead of .filter()
as you’re not filtering and using the array that .filter()
returns.
Here is another appraoch that involes creating a Map (similar to an object), that holds the frequency for each char as a value. Using .replace()
we can return a new string where we replace each character based on if it appears multiple times or not:
const duplicateEncode = (word) => { const lower = word.toLowerCase(); const charFreq = [...lower].reduce((map, c) => map.set(c, (map.get(c) ?? 0) + 1), new Map); return lower.replace(/./ug, (c) => charFreq.get(c) === 1 ? "(" : ")"); } console.log(duplicateEncode("din")); // "(((" console.log(duplicateEncode("recede")); // "()()()" console.log(duplicateEncode("Success")); // ")())())" console.log(duplicateEncode("(( @")); // "))((" console.log(duplicateEncode("nGnnI)nPne@uwJ")); // ")())(()()((((("