JSFiddle - React, Tailwind, and code Playground

by kkdaily

HTML

<h3>
(CTCI 1.4) given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. a permutation is a rearrangement of letters. the palindrome does not need to be limited to just dictionary words. (ex: Tact Coa => true (permutations: "taco cat", "acto cta", etc))
</h3>

<div id="message"></div>

CSS

#message {
  padding: 10px;
}

.success {
  background-color: lightgreen;
}

.failure {
  background-color: pink;
}

JavaScript

// 1. if the length of the str is 0, return an error
// 2. if the length of the str is 1, return true
// 3. if the length of the str is even, then there has to be an even number of all chars
// 4. if the length of the str is odd, then there has to be only 1 char that appears an odd number of times while all other chars must appear an even number of times
// 5. get rid of spaces (str.trim().split('').join(' '))
// 6. break out string into chars (str.split(''))
// 6. create hash table to store seen chars ( seenChars = {} )
// 6. create a isPermutationOfPalindrome var and set it to true
// 7. iterate over chars ( for loop )
// 8. check if the current char is present in the seenChars hash ( if (seenChars[currentChar]))
// 9. if so, then increment by 1 ( seenChars[currentChar]++ )
// 10. otherwise, add the char as a new key ( seenChars[currentChar] = 1 )
// 11. once done looping, check if str has an even length ( if (str.length % 2 === 0) )
// 12. if it is even, then check if all of the keys in the hash table have even values ( keys = Object.keys(seenChars) ... keys.forEach((key) => { if (seenChars[key] % 2 !== 0) { isPermutationOfPalindrome = false }}))
// 13. if it is odd, then check if there is 1 key in the hash table with an odd value. If not, then set isPermutationOfPalindrome to false. Otherwise, check if all other keys are even. If not, then also false

isPermutationOfPalindrome = (str) => {
	if (!str.length) {
  	return new Error('string must have at least one character')
  }
  
  if (str.length === 1) {
		return true
	}
  
  const chars = str.trim().toLowerCase().split('').join(' ').split('')
  const seenChars = {}
  let isPermutationOfPalindrome = true
  
  for (let i = 0; i < chars.length; i++) {
		if (seenChars[chars[i]]) {
    	seenChars[chars[i]]++
    } else {
    	seenChars[chars[i]] = 1
    }
  }
  
  const keys = Object.keys(seenChars)
  
  // if the str has an even number of chars
  if (chars.length % 2 === 0) {
  	keys.forEach((key) => {
    	if...