Skip to content

Instantly share code, notes, and snippets.

@Echooff3
Created January 15, 2021 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Echooff3/1f9c4c046be2b72d85c2764837b6ada3 to your computer and use it in GitHub Desktop.
Save Echooff3/1f9c4c046be2b72d85c2764837b6ada3 to your computer and use it in GitHub Desktop.
Palindrome
const isPalindrome = str => [...str].reverse().join('') === str
const canBePalindrome = str => {
const res = [...str].reduce((a,c) => {
a[c] = !a[c] ? 1 : a[c]+1
return a
}, {})
//there needs to be 1 odd number letter and the reset even
const check = Object.entries(res).map(x => {
return x[1] % 2
}).reduce((a,c) => a+c)
// Check should contain the number of letters that are odd numbered
// if > 1 then it's a no go
return check === 1
}
// is pal
console.log('isPalindrome()')
console.log(`\tracecar should be true`, isPalindrome(`racecar`))
console.log(`\tracec should be false`, isPalindrome(`racec`))
// can be pal
console.log('canBePalindrome()')
console.log(`\tracecar should be true`, canBePalindrome(`racecar`))
console.log(`\trraacce should be true`, canBePalindrome(`rraacce`))
console.log(`\tracec should be false`, canBePalindrome(`racec`))
console.log(`\taabbcbbaa should be true`, canBePalindrome(`aabbcbbaa`))
console.log(`\taabbc should be true`, canBePalindrome(`aabbc`))
console.log(`\tabc should be false`, canBePalindrome(`racec`))
@Echooff3
Copy link
Author

Results

isPalindrome()
	racecar should be true true
	racec should be false false
canBePalindrome()
	racecar should be true true
	rraacce should be true true
	racec should be false false
	aabbcbbaa should be true true
	aabbc should be true true
	abc should be false false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment