mercredi 29 juillet 2015

Javascript: palindrome function?

I have working code for a simple word flipper:

var strFlip = function(str) {
    return str.split(" ").map(function(word) {
        return word.split("").reverse().join("");
    }).join(" ");    
};

console.log(strFlip("This is designed to swap the letter order of each word in the string"));

// "sihT si dengised ot paws eht rettel redro fo hcae drow ni eht gnirts"

I want to add an if/else to allow this code to now identify if each word in a string is a palindrome (spelled the same forward and backward ex: hannah).

So I tried continuing the .map() logic with:

var strFlip = function(str) {
  return str.split(" ").map(function(word) {
    return word.split("").reverse().join("");
      }).join(" ").toLowerCase().map(function(test) {
    if (test.split(" ") === word){
      return true;
    }else{
      return false;
    }
  }
   );
};

console.log(strFlip("Hannah loves her racecar"));

BUT.... unsurprisingly, it returns an error essentially stating that the long linked collection of functions before the if section is not itself a function:

TypeError: str.split(...).map(...).join(...).toLowerCase(...).map is not a function

I was also getting lost trying to match all of the curly braces, but I think I got them all.

So, is it possible to add the if/else within?

Aucun commentaire:

Enregistrer un commentaire