CheckRearrangePalindrome.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * What is a palindrome? https://en.wikipedia.org/wiki/Palindrome
  3. * Receives a string and returns whether it can be rearranged to become a palindrome or not
  4. * The string can only be a palindrome if the count of ALL characters is even or if the ONLY ONE character count is odd
  5. * Input is a string
  6. *
  7. **/
  8. export const palindromeRearranging = (str) => {
  9. // check that input is a string
  10. if (typeof str !== 'string') {
  11. return 'Not a string'
  12. }
  13. // Check if is a empty string
  14. if (!str) {
  15. return 'Empty string'
  16. }
  17. // First obtain the character count for each character in the string and store it in an object.
  18. // Filter the object's values to only the odd character counts.
  19. const charCounts = [...str].reduce((counts, char) => {
  20. counts[char] = counts[char] ? counts[char] + 1 : 1
  21. return counts
  22. }, {})
  23. // If the length of the resulting array is 0 or 1, the string can be a palindrome.
  24. return (
  25. Object.values(charCounts).filter((count) => count % 2 !== 0).length <= 1
  26. )
  27. }
  28. // testing
  29. // > palindromeRearranging('aaeccrr')
  30. // true
  31. // > palindromeRearranging('leve')
  32. // false