| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const findAnagrams = () => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | export const findAnagrams = (target, candidates) => { |
| 7 | // Edge Case: Handle null or undefined inputs |
| 8 | if (!target || !candidates) { |
| 9 | return []; |
| 10 | } |
| 11 | |
| 12 | // Edge Case: Handle non-array candidates |
| 13 | if (!Array.isArray(candidates)) { |
| 14 | return []; |
| 15 | } |
| 16 | |
| 17 | // Normalize target to lowercase for comparison |
| 18 | const normalizedTarget = target.toLowerCase(); |
| 19 | |
| 20 | // Create a sorted string of the target's characters for anagram comparison |
| 21 | const sortedTarget = normalizedTarget.split('').sort().join(''); |
| 22 | |
| 23 | // Filter candidates to find anagrams |
| 24 | return candidates.filter(candidate => { |
| 25 | // Edge Case: Handle null or undefined candidate |
| 26 | if (candidate === null || candidate === undefined) { |
| 27 | return false; |
| 28 | } |
| 29 | |
| 30 | // Edge Case: Handle non-string candidate |
| 31 | if (typeof candidate !== 'string') { |
| 32 | return false; |
| 33 | } |
| 34 | |
| 35 | // Edge Case: Words with different lengths cannot be anagrams |
| 36 | if (candidate.length !== target.length) { |
| 37 | return false; |
| 38 | } |
| 39 | |
| 40 | // Edge Case: A word is not its own anagram (case insensitive) |
| 41 | if (candidate.toLowerCase() === normalizedTarget) { |
| 42 | return false; |
| 43 | } |
| 44 | |
| 45 | // Check if candidate is an anagram by comparing sorted characters |
| 46 | const normalizedCandidate = candidate.toLowerCase(); |
| 47 | const sortedCandidate = normalizedCandidate.split('').sort().join(''); |
| 48 | |
| 49 | return sortedCandidate === sortedTarget; |
| 50 | }); |
| 8 | 51 | }; |
| 52 | |
| 53 | // Handled Edge Cases: null/undefined inputs, non-array candidates, null/undefined candidates, non-string candidates, different length strings, identical words (case insensitive) |