0
\$\begingroup\$

The code below is for checking whether the input string is palindrome or not

const { argv } = require("process");

(()=>{
    var palindrom01 = palindrom01;
    
    palindrom01();

    function palindrom01(){

        let inputNum = argv[2];
        let totalLength = inputNum.length;
        let half_length = parseInt(totalLength/2);
        let flag = true; 
        
        for(let i = 0, j = (totalLength - 1); i < half_length; i++){
            if(inputNum.charAt(i) !== inputNum.charAt(j)){
                flag = false;    
                break;
            }
            j--;
        }

        console.log(`input ${inputNum} is Palinform => ${flag}`);
    }
})();

This is the output of the code

D:\> node .\palindrom.js 12321
input 12321 is Palinform => true
D:\> node .\palindrom.js 123321
input 123321 is Palinform => true
D:\> node .\palindrom.js 12345
input 12345 is Palinform => false
D:\>

Is Panlindrome properly implemented? if yes, is there a way better way to do it ?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

From a short review;

  • palindrom01 does too much

    1. it finds the input
    2. it determines whether the input is a palindrome
    3. it prints to the console These could be 3 different functions
  • var palindrom01 = palindrom01; -> I guess you are trying to hoist the function to the top or something. However, you can remove this complete

  • palindrom01 is not a great function name, I would go for isPalindrome(s) which returns a boolean

  • Most people consider the best approach a split to an array of characters, reverse, concatenate and compare to the original again

  • In general I like self-executing functions, but it seems, in this case, it is overkill

This is my counter-example,

function getInput(){
  return Input.value;
}

function isPalindrome(s){
  return s === s.split('').reverse().join('');
}

function showIsPalindrome(s){
  console.log( `${s} is${isPalindrome(s)?'':' not'} a palindrome` );
}

function controller(event){
  const enterKey = 13;
  if(event.keyCode === enterKey){
    showIsPalindrome(getInput());
  }
}

Input.addEventListener('keypress', controller);
<input id='Input'></input>

\$\endgroup\$
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.