I wonder how to write palindrome in javascript, where I input different words and program shows if word is palindrome or not. For example word noon is palindrome, while bad
All these loops! How about some functional goodness :) May run in to tail call issues on old/current js engines, solved in ES6
function isPalendrome(str){
var valid = false;
if(str.length < 2 ) return true;
function even(i,ii){
str[i]===str[ii] ? ((i+1 !== ii) ? even(i+1,ii-1) : valid = true) : null
}
function odd(i, ii){
str[i]===str[ii] ? ((i !== ii) ? odd(i+1,ii-1) : valid = true) : null
}
if(str.length % 2){
return odd(0,str.length-1),valid;
}else{
return even(0,str.length-1),valid;
}
}
To test your call stack run this code, you will be able to parse strings double the call stack size
function checkStackSize(){
var runs = 70000;
var max_process = 1;
var max = 0;
function recurse_me() {
max_process++;
if(max_process === runs) return;
max = max_process;
try {
recurse_me()
} catch(e) {
max = max_process;
}
}
recurse_me()
console.log(max);
}
Due to the symmetrical nature of the problem you could chunk the string from the outside in and process the chunks that are within call stack limits.
by that I mean if the palindromes length is 1000. You could join 0-250 and 750-1000 and join 250-499 with 500-749. You can then pass each chunk in to the function. The advantage to this is you could run the process in parallel using web workers or threads for very large data sets.
The code is concise quick fast and understandable.
TL;DR
Explanation :
Here isPalindrome
function accepts a str
parameter which is typeof string.
If the above case is false then it moves on to the second if statement and checks that if the character at 0 position of the string is same as character at the last place. It does an inequality test between the both.
str.charAt(0) // gives us the value of character in string at position 0
str.slice(-1) // gives us the value of last character in the string.
If the inequality result is true then it goes ahead and returns false.
isPalindrome(str)
function over and over again until the final result. function isPalindrome(str){
if (str.length <= 1) return true;
if (str.charAt(0) != str.slice(-1)) return false;
return isPalindrome(str.substring(1,str.length-1));
};
document.getElementById('submit').addEventListener('click',function(){
var str = prompt('whats the string?');
alert(isPalindrome(str))
});
document.getElementById('ispdrm').onsubmit = function(){alert(isPalindrome(document.getElementById('inputTxt').value));
}
<!DOCTYPE html>
<html>
<body>
<form id='ispdrm'><input type="text" id="inputTxt"></form>
<button id="submit">Click me</button>
</body>
</html>
I am not sure how this JSPerf check the code performance. I just tried to reverse the string & check the values. Please comment about the Pros & Cons of this method.
function palindrome(str) {
var re = str.split(''),
reArr = re.slice(0).reverse();
for (a = 0; a < re.length; a++) {
if (re[a] == reArr[a]) {
return false;
} else {
return true;
}
}
}
JS Perf test
Try this:
var isPalindrome = function (string) {
if (string == string.split('').reverse().join('')) {
alert(string + ' is palindrome.');
}
else {
alert(string + ' is not palindrome.');
}
}
document.getElementById('form_id').onsubmit = function() {
isPalindrome(document.getElementById('your_input').value);
}
So this script alerts the result, is it palindrome or not. You need to change the your_id
with your input id and form_id
with your form id to get this work.
Demo!
function palindrome(str){
for (var i = 0; i <= str.length; i++){
if (str[i] !== str[str.length - 1 - i]) {
return "The string is not a palindrome";
}
}
return "The string IS a palindrome"
}
palindrome("abcdcba"); //"The string IS a palindrome"
palindrome("abcdcb"); //"The string is not a palindrome";
If you console.log this line: console.log(str[i] + " and " + str[str.length - 1 - i])
, before the if statement, you'll see what (str[str.length - 1 - i])
is. I think this is the most confusing part but you'll get it easily when you check it out on your console.
Faster Way:
-Compute half the way in loop.
-Store length of the word in a variable instead of calculating every time.
EDIT: Store word length/2 in a temporary variable as not to calculate every time in the loop as pointed out by (mvw) .
function isPalindrome(word){
var i,wLength = word.length-1,wLengthToCompare = wLength/2;
for (i = 0; i <= wLengthToCompare ; i++) {
if (word.charAt(i) != word.charAt(wLength-i)) {
return false;
}
}
return true;
}