r/shittyprogramming • • Jun 07 '21
isEven with regex in javascript
const isEven = n => 'x'.repeat(n).replace(/xx/g, '') === '';
102
Upvotes
r/shittyprogramming • • Jun 07 '21
const isEven = n => 'x'.repeat(n).replace(/xx/g, '') === '';
View all comments
Show parent comment
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