DEV Community

Discussion on: Anagrams Checker - Three JavaScript Solutions

Collapse
 
calebpitan profile image
Caleb Adepitan • Edited

What do you think?

function anagrams(a, b) {
  let i = 0
  let sumA = 0
  let sumB = 0
  a = a.replace(/[\W]/g, "").toLowerCase()
  b = b.replace(/[\W]/g, "").toLowerCase()
  if (a.length !== b.length) return false
  !(function sumCharCode() {
    if (i < a.length) {
      sumA += a.charCodeAt(i)
      sumB += b.charCodeAt(i)
      i++
      sumCharCode()
    }
  })()
  return sumA === sumB;
}

console.log(anagrams("listen", "silent"))

Enter fullscreen mode Exit fullscreen mode

Copyright (c) 2019 Caleb Pitan
😇😁😁

Collapse
 
joeberetta profile image
Joe Beretta

I thought about using \W instead of ^w as you wrote)

Collapse
 
calebpitan profile image
Caleb Adepitan

There's really no difference, it's just left to choice.

Thread Thread
 
joeberetta profile image
Joe Beretta

Know it. But I think this way is more elegant and perfomance

Collapse
 
moopet profile image
Ben Sinclair

I think that function expressions using ! are there just to make the code less readable.

Collapse
 
calebpitan profile image
Caleb Adepitan • Edited

My bad! I won't lie to you I really don't know the use of the "!", but I think it's to indicate an iife inside the function, hence aid readability. I put it because in my early years I saw a lot of these around, and I thought having it around or not affects nothing. Didn't know it affects readability, although I don't understand how. I wouldn't mind if you told me.

Thread Thread
 
moopet profile image
Ben Sinclair

I prefer explicit to implicit (comes from enjoying Python too much...) and !(function(){...}(); is just... well, if you haven't seen it before you have no idea what the gosh darnit is going on.

Thread Thread
 
calebpitan profile image
Caleb Adepitan
Collapse
 
lexlohr profile image
Alex Lohr

I initially thought about that approach, but discarded it for an obvious reason:

anagrams('abc', 'aad') // => true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
calebpitan profile image
Caleb Adepitan

Smart 😃.
It's just too obvious. Didn't take time to analyze it. It struck my mind as I saw this post and I put it down.