Search code examples
javascriptphpisset

isset equivalent in javascript to find palindrome


I created a script in PHP to find a palindrome, but when I try to do the same in JavaScript, then it is not working as expected. It's not just a matter of checking if the string that is reversed matches, but any order of the string has to be checked as well.

In other words, "mom" should return as true, "mmo" should return as true, "omm" should return as true, etc..., which is what the PHP script does, but the JS script below doesn't even work for the first iteration for the string "mom"

The following is the PHP script:

<?php
function is_palindrom($str) {

$str_array = str_split($str);
$count = array();

foreach ($str_array as $key) {
  if(isset($count[$key])) {
    $count[$key]++;
  } else {
    $count[$key] = 1;
  }
}

$odd_counter = 0;
foreach ($count as $key => $val) {
  if(($val % 2) == 1) {
    $odd_counter++;
  }
}

return $odd_counter <= 1;
}

echo is_palindrom('mom') ? "true" : "false";

The following is what I have tried in JS:

var count = [];
var strArr = [];
var oddCounter = 0;

var foreach_1 = function(item, index) {
 console.log("count[index]: " + count[index]);
 if (typeof count[index] !== "undefined") {
  count[index]++;
 } else {
  count[index] = 1;
 }
};

var foreach_2 = function(item, index) {
console.log("item: " + item + " item % 2: " + eval(item % 2));
 if (eval(item % 2) == 1) {
  oddCounter++;
 }
 console.log("oddCounter: " + oddCounter);
 return oddCounter <= 1;
};

var isPalindrom = function(str) {
 strArr = str.split("");
 console.log(strArr);

 strArr.forEach(foreach_1);
 console.log(count);

 count.forEach(foreach_2);
};

I believe it is failing where I try to replicate isset in javascript, with the following code:

if (typeof count[index] !== "undefined") {

As a result, I have tried to write my own isset function, but still the same result, it is not working:

 var isset = function(obj) {
  if (typeof obj === "undefined" || obj === null) {
    return false;
  } else {
    return true;
  }
};

With the following function being called:

  if (isset(count[index])) {
    count[index]++;
  } else {
    count[index] = 1;
  }

As usual, any help would be appreciated and thanks in advance

BTW, it's killing me that I cannot remember the word for several revisions or iterations of something - I know that it starts with "re"


Solution

  • First, thank you for all the comments.

    Second, I ran a var_dump on the count array in the PHP file and this was the result:

    array (size=2)
    'm' => int 2
    'o' => int 1
    

    Which lead me to understand that count in js has to be an object for this work and I would have to create indexes of the object, depending on the string entered.

    One thing lead to another and a complete re-write, but it works, along with a spell checker - see link at the bottom for complete code:

    var count = {};
    var strArr = [];
    var oddCounter = 0;
    var objKeys = [];
    var splitString;
    var reverseArray;
    var joinArray;
    var url = "test-spelling.php";
    var someRes = "";
    
    var mForN = function(obj, strArr) {
      for (var y = 0; y < strArr.length; y++) {
        // console.log("obj[strArr[" + y + "]]: " + obj[strArr[y]]);
        if (isset(obj[strArr[y]])) {
          obj[strArr[y]]++;
        } else {
          obj[strArr[y]] = 1;
        }
      }
      return obj;
    };
    
    var mForN_2 = function(obj, objKeys) {
      for (var z = 0; z < objKeys.length; z++) {
        /* console.log(
          "obj[objKeys[z]]: " +
            obj[objKeys[z]] +
            " obj[objKeys[z]] % 2: " +
            eval(obj[objKeys[z]] % 2)
        ); */
        if (eval(obj[objKeys[z]] % 2) == 1) {
          oddCounter++;
        }
        // console.log("oddCounter: " + oddCounter);
      }
    
      return oddCounter <= 1;
    };
    
    var isset = function(obj) {
      if (typeof obj === "undefined" || obj === null) {
        return false;
      } else {
        return true;
      }
    };
    
    var isPalindrom = function(str) {
      // reverse original string
      splitString = str.split("");
      reverseArray = splitString.reverse();
      joinArray = reverseArray.join("");
    
      var checking = checkSpellingOfStr(str);
    
      if (str == joinArray) {
        strArr = str.split("");
        // console.log("strArr: " + strArr);
    
        objKeys = makeObjKeys(count, strArr);
        // console.log("filled count before mForN: " + JSON.stringify(count));
    
        // create array of keys in the count object
        objKeys = Object.keys(count);
        // console.log("objKeys: " + objKeys);
    
        count = mForN(count, strArr);
        // console.log("count after mForN: " + JSON.stringify(count));
    
        return mForN_2(count, objKeys);
      } else {
        return 0;
      }
    };
    
    var makeObjKeys = function(obj, arr) {
      for (var x = 0; x < arr.length; x++) {
        obj[arr[x]] = null;
      }
      return obj;
    };
    
    var checkSpellingOfStr = function(someStr) {
      var formData = {
        someWord: someStr
      };
    
      $.ajax({
        type: "GET",
        url: url,
        data: formData,
        success: function(result) {
          if (!$.trim(result)) {
          } else {
            console.log(result);
            $("#checkSpelling").html(result);
          }
        }
      });
    };
    

    Start everything with the following call:

    isPalindrom("mom") ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
    

    In my example, I have a form and I listen for a button click as follows:

    var palindromeTxt = document.getElementById("palindromeTxt").value;
    var btn = document.getElementById("button");
    btn.addEventListener("click", function (event) {
      isPalindrom(palindromeTxt) ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
    });
    

    The following is the php for spell check:

    <?php
    error_reporting(E_ALL); 
    ini_set('display_errors', 1);
    
    if(!empty($_REQUEST['someWord']))
    {
        $someWord = $_REQUEST['someWord'];
    }
    
    $pspell_link = pspell_new("en");
    
    if (pspell_check($pspell_link, $someWord)) {
      echo trim($someWord) . " is a recognized word in the English language";
    } else {
      echo "Your word is either misspelled or that is not a recognized word";
    }
    

    You will need pspell installed on your server, as well as adding extension=pspell.so to your php.ini

    This is what I did, to get it running locally on my mac:

    cd /Users/username/Downloads/php-5.6.2/ext/pspell 
    
    /usr/local/bin/phpize
    
    ./configure --with-php-config=/usr/local/php5-5.6.2-20141102-094039/bin/php-config --with-pspell=/opt/local/
    
    make
    
    cp ./modules/* /usr/local/php5-5.6.2-20141102-094039/lib/php/extensions/no-debug-non-zts-20131226
    
    sudo apachectl restart
    
    check your phpinfo file and you should see the following:
    
    pspell
    PSpell Support  enabled
    

    Live example