$17.59

Make a palindrome.

Ask a question+
2

Function that receives a string and returns the final palindrome.
input abcdc , output abcdcba

add comment

1 Answer

2
function reverseString(str) {
    return str.split('').reverse().join('');
}

function isPalindrome(str) {
    return str === reverseString(str);
}

function makePolindrome(str) {
    if (str === "") {
        return "";
    }

    if (str[0] === str[str.length - 1]) {
        const subStr = str.substr(1, str.length - 2);
        return isPalindrome(subStr) ? str : str + reverseString(subStr) + str[0];
    } else {
        const subStr = str.substr(1, str.length - 1);
        return str[0] + makePolindrome(subStr) + str[0];
    }
}

function makePolindrome checks if first character and last character are the same

  • if str[0] === str[str.length - 1]
    checks if str is polindrome
    • if yes, returns that string
    • if no, concatenates str and reverse of str without the first character and returns result
  • if str[0] !== str[str.length - 1]
    inserts str[0] at the start and end of makePolindrome(str.substring(1, str.length - 1)) and returns result
darbinyanraf 130
add comment

Your Answer