Make a Palindrome

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
function makePalindrome(text){
function check(s){
return s.split('').reverse().join('') == s;
}
if(check(text)) return text;
var minhead, minheadi;
//check head
for(var i = 1; i <= text.length; i++){
var s = text + text.substr(0,i).split('').reverse().join('');
if(check(s)){
minhead = s;
minheadi = i;
break;
}
}
//check tail
for(var i = 1; i < minheadi; i++){
var s = text.substr(-i).split('').reverse().join('') + text;
if(check(s)) return s;
}
return minhead;
}