-
Notifications
You must be signed in to change notification settings - Fork 1
/
palindrome.js
executable file
·67 lines (62 loc) · 1.63 KB
/
palindrome.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var freq = {}
/// BORROWED reverse() and repeat()
function reverse(string) {
return string.split("").reverse().join("");
}
function repeat(str, num) {
return (new Array(num+1)).join(str);
}
/// UTILITY
// sets up letters frequency map
function countLetters(string) {
var freq = {}
for (var letter of string.split("")) {
freq.hasOwnProperty(letter) ? freq[letter]++ : freq[letter] = 1
}
return freq;
}
// find the odd letter, decrements its freq value
function findOdd(string) {
for (var key in freq) {
if (freq[key] % 2 !== 0) {
freq[key] -= 1
return key;
}
}
}
/// MAIN FUNCTIONS
function isPalindrome(string) {
return string == reverse(string) ? true : false
}
// Makes sure only one letter occurs an odd number of times
function canBePalindrome(string) {
var numberOfOdds = 0,
freq = countLetters(string)
for (var key in freq) {
if (freq[key] % 2 !== 0) {
numberOfOdds += 1
}
}
return numberOfOdds > 1 ? false : true
}
// Creates palindrome from a candidate string
function createPalindrome(string) {
var palindrome = findOdd(string);
for (var key in freq) {
if(freq[key] > 0) {
palindrome = repeat(key, (freq[key] / 2)).concat(palindrome)
palindrome += repeat(key, (freq[key] / 2))
}
}
return palindrome;
}
function main(string) {
freq = countLetters(string);
if(isPalindrome(string)) {
console.log(string.concat(" is already a palindrome."))
} else if(!canBePalindrome(string)) {
console.log(string.concat(" cannot be made into a palindrome."))
} else {
console.log((string.concat(" as a palindrome: ")).concat(createPalindrome(string)))
}
}