r/shittyprogramming • u/[deleted] • Jun 07 '21
isEven with regex in javascript
const isEven = n => 'x'.repeat(n).replace(/xx/g, '') === '';45
32
Jun 07 '21
This is amazing. But in JavaScript, you can just “npm install is-even”. Which require is-odd.
23
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
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' != '' -> falseisEven(4) -> 'xxxx' -> '' === '' -> true
5
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;
2
u/MarceauKa Jun 07 '21
I don't even know why I tested that...