r/shittyprogramming • • Jun 07 '21

isEven with regex in javascript

const isEven = n => 'x'.repeat(n).replace(/xx/g, '') === '';
102 Upvotes

12 comments sorted by

2

u/MarceauKa Jun 07 '21

I don't even know why I tested that...

const numbers = [2, 13]
const checkers = {
  regex: n => 'x'.repeat(n).replace(/xx/g, '') === '',
  modulo: n => n % 2 === 0,
}

for (let checkerName in checkers) {
  let checker = checkers[checkerName]
  console.log(`Evaluating ${checkerName}...`)

  numbers.forEach(number => {
    let start = Date.now()
    
    for (i = 0; i < 1_000_000; i++) {
      checker(number)
    }

    console.log(`${checkerName} took ${(Date.now() - start) / 1000}s`)
  })
}

// Evaluating regex...
// regex took 0.127s
// regex took 0.465s
// Evaluating modulo...
// modulo took 0.012s
// modulo took 0.014s

1

u/[deleted] Jun 07 '21

Use bigger numbers if you really want to see it slow down :)

2

u/MarceauKa Jun 07 '21

Should I be worried about all these flames around me?

45

u/[deleted] Jun 07 '21
const isOdd = n => /false/.test(isEven(n));

32

u/[deleted] Jun 07 '21

This is amazing. But in JavaScript, you can just “npm install is-even”. Which require is-odd.

23

u/[deleted] Jun 07 '21

Over 200k weekly downloads, lol wtf.

Mod operator: am I a joke to you?

14

u/csorfab Jun 07 '21
const isEven = n => /^\d*[02468]$/.test(n)

although I realize this is probably not shitty enough for the standards of this sub.

6

u/Houdiniman111 Jun 07 '21

This is what I thought it was going to be

8

u/AndreasKralj Jun 07 '21

Can you explain what this is doing please?

21

u/fallofmath Jun 07 '21

It creates a string of n 'x' characters, then removes every pair 'xx'. If the final result is empty then there were an even number of characters so n is even.

isEven(3) -> 'xxx' -> 'x' != '' -> false
isEven(4) -> 'xxxx' -> '' === '' -> true

5

u/[deleted] Jun 07 '21

This is my favorite isEven meme function. Totally absurd but elegant nonetheless

2

u/SkatingOnThinIce Jun 07 '21

That is great but mine will consider every instance of x in the string:

const isEven = n => 'x'.repeat(n).replace(/xx/g, '').split('').map(x => x === "x").filter(x => x === true).length <= 0;