-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calculate Parity bit!
22 lines (14 loc) · 945 Bytes
/
Calculate Parity bit!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
A parity bit, or check bit, is a bit added to a string of bits to ensure that the total number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code.
You have two parameters, one being the wanted parity (always 'even' or 'odd'), and the other being the binary representation of the number you want to check.
Your task is to return an integer (0 or 1), whose parity bit you need to add to the binary representation so that the parity of the resulting string is as expected.
Example:
Parity: 'even'
Bin: '0101010'
Result: 1
Because there is an odd number of 1-bits (3) you need to put another 1 to it to get an even number of 1-bits.
*/
export function checkParity(parity: string, bin: string) {
return parity === 'odd' ? ([...bin].filter(el=>el === '1').length % 2 === 0 ? 1 : 0)
: (parity === 'even' ? ([...bin].filter(el=>el === '1').length % 2 === 0 ? 0:1):-1)
}