Palindromes

A palindrome is a word that it is spelled the same forward than backward. For example “ROTOR

Pseudo-code

  1. If string has no letters or just one letter then it is a palindrome.
  2. Otherwise, compare first and last letters of the string. If they differ it is not a palindrome.
  3. Keep doing the same until you end up with one letter or 0

Implementation

  1. // Returns the first character of the string str
  2. var firstCharacter = function(str) {
  3. return str.slice(0, 1);
  4. };
  5. // Returns the last character of a string str
  6. var lastCharacter = function(str) {
  7. return str.slice(-1);
  8. };
  9. // Returns the string that results from removing the first
  10. // and last characters from str
  11. var middleCharacters = function(str) {
  12. return str.slice(1, -1);
  13. };
  14. var isPalindrome = function(str) {
  15. // base case #1
  16. if (str.length <= 1) {
  17. return true;
  18. }
  19. // base case #2
  20. if (firstCharacter(str) !== lastCharacter(str)) {
  21. return false;
  22. }
  23. // recursive case
  24. return (firstCharacter(str) === lastCharacter(str)) && isPalindrome(middleCharacters(str));
  25. };
  26. var checkPalindrome = function(str) {
  27. println("Is this word a palindrome? " + str);
  28. println(isPalindrome(str));
  29. };
  30. checkPalindrome("a");
  31. Program.assertEqual(isPalindrome("a"), true);
  32. checkPalindrome("motor");
  33. Program.assertEqual(isPalindrome("motor"), false);
  34. checkPalindrome("rotor");
  35. Program.assertEqual(isPalindrome("rotor"), true);