| 7 | * @example parityOutlier([1, 3, 5, 8, 9]) = 8 |
| 8 | */ |
| 9 | const parityOutlier = (integers) => { |
| 10 | let oddsCount = 0 // define counter for odd number(s) |
| 11 | let evensCount = 0 // define counter for even number(s) |
| 12 | let odd, even |
| 13 | |
| 14 | for (const e of integers) { |
| 15 | if (!Number.isInteger(e)) { |
| 16 | // detect non-integer elements |
| 17 | return null |
| 18 | } |
| 19 | if (e % 2 === 0) { |
| 20 | // an even number |
| 21 | even = e |
| 22 | evensCount++ |
| 23 | } else { |
| 24 | // an odd number |
| 25 | odd = e |
| 26 | oddsCount++ |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | if (oddsCount === 0 || evensCount === 0) return null // array has only odd/even number(s) |
| 31 | if (oddsCount > 1 && evensCount > 1) return null // array has more than one even and odd number |
| 32 | |
| 33 | return oddsCount === 1 ? odd : even |
| 34 | } |
| 35 | |
| 36 | export { parityOutlier } |