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

View all comments

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?