DEV Community

David
David

Posted on

3 2

Code Golf Challenge: Palindrome Detector

Challenge: Using Javascript, implement a method that detects if a string is a palindrome in as few characters as possible!

The goal of this exercise is to write as little code as possible. Readability and maintainability are not a concern!

Solutions in comments πŸ‘‡πŸ‘‡

Top comments (14)

Collapse
 
quickhand profile image
quickhand β€’

Short:

let p=s=>![...s].some((c,i,a)=>c!=a[a.length-i-1])

Shorter:

let p=s=>[...s].reverse().join("")==s

In both:

p("potato") //false
p("racecar") //true

(First works on palindromic arrays of characters as well as strings, second only on strings)

Collapse
 
daveturissini profile image
David β€’

Nice. Really like the approach with β€œsome” in your first example

Collapse
 
maxart2501 profile image
Massimo Artizzu β€’ β€’ Edited
[...word].reverse().join('')==word
Enter fullscreen mode Exit fullscreen mode

On the plus side, it works on emojis (.split('') doesn't), but not on complex ones (like πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦).

Collapse
 
siddharthshyniben profile image
Siddharth β€’

you can shave off 2 chars by doing .join``

Collapse
 
shijiezhou profile image
Shijie Zhou β€’
function palindrome(str) {
    var splitString = str.split("");
    var halfSplitString = splitString.length / 2;
    for (var i = 0; i < halfSplitString; i++) {
        if (str[i] !== str[str.length - i - 1]) {
            return false;
        }
        else {
            return true;
        }
    }
}
Collapse
 
aspenjames profile image
Aspen James β€’

Does this need to work on palindromes containing capitalization, spaces, punctuation, etc?

For example: "A man, a plan, a canal: Panama." - some would consider this a palindrome, some would

Collapse
 
daveturissini profile image
David β€’

Good question. Lets keep it simple: only checking for words. No handling for spaces, punctuation or numbers.

Collapse
 
daveturissini profile image
David β€’ β€’ Edited

Nice! You can make the function even smaller if you just returned



Array.from(word)
.reverse()
.join("") === word
Collapse
 
wheatup profile image
Hao β€’

Even shorter

word.split('').reverse().join('')==word
Thread Thread
 
nataliedeweerd profile image
𝐍𝐚𝐭𝐚π₯𝐒𝐞 𝐝𝐞 π–πžπžπ«π β€’

This wouldn't work for "Arara" would it? It'd need some sort of case normalisation.

Also, what about "Taco cat".

Thread Thread
 
quickhand profile image
quickhand β€’ β€’ Edited

The issuer of the challenge, David, said:
"Lets keep it simple: only checking for words. No handling for spaces, punctuation or numbers."

But if we're handling capitals and spaces, how about:

let p=s=>(t=>[...t].reverse().join("")==t)(s.toLowerCase().replace(/\s/g,""))

Here,

p("Taco cat") //returns true,
p("Arara") //returns true

Another slight mod and we can ignore all non-letter chars (numbers, punctuation, etc.):

let p=s=>(t=>[...t].reverse().join("")==t)(s.toLowerCase().replace(/[^A-z]/g,""))

p("A man, a plan, a canal: Panama.") // returns true
Collapse
 
daveturissini profile image
David β€’ β€’ Edited
let p = (w) => { let i = 0,c = w[i],l=w.length - 1;while(c){if(c !== w[l-i]){return false}c=w[++c]}return true}
Collapse
 
siddharthshyniben profile image
Siddharth β€’

This is the shortest IMO:

s=>[...s].reverse``.join``==s
Enter fullscreen mode Exit fullscreen mode

With normalization:

s=>{s=s.replace(/\s/g,'').toLowerCase();return[...s].reverse``.join``==s}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
n8chz profile image
Lorraine Lee β€’
function p(a) {while (a.length>1&&(v=a.shift()==a.pop())); return v;}

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay