-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
ParityOutlier.js
36 lines (32 loc) · 1 KB
/
ParityOutlier.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* @author mrmagic2020
* @description The function will find the parity outlier from an array of integers.
* @see https://en.wikipedia.org/wiki/Parity_(mathematics)
* @param {number[]} integers - An array of integers.
* @returns {number} - The parity outlier.
* @example parityOutlier([1, 3, 5, 8, 9]) = 8
*/
const parityOutlier = (integers) => {
let oddsCount = 0 // define counter for odd number(s)
let evensCount = 0 // define counter for even number(s)
let odd, even
for (const e of integers) {
if (!Number.isInteger(e)) {
// detect non-integer elements
return null
}
if (e % 2 === 0) {
// an even number
even = e
evensCount++
} else {
// an odd number
odd = e
oddsCount++
}
}
if (oddsCount === 0 || evensCount === 0) return null // array has only odd/even number(s)
if (oddsCount > 1 && evensCount > 1) return null // array has more than one even and odd number
return oddsCount === 1 ? odd : even
}
export { parityOutlier }