-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
53 lines (47 loc) · 991 Bytes
/
index.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
var assert = require('assert');
module.exports = compare;
function compare(a, b) {
a = hexToBinary(a)
b = hexToBinary(b)
assert.equal(a.length, b.length, 'Argument must have equal lengths.');
return hammingDistance(a, b);
}
var lookup = {
'0': '0000',
'1': '0001',
'2': '0010',
'3': '0011',
'4': '0100',
'5': '0101',
'6': '0110',
'7': '0111',
'8': '1000',
'9': '1001',
'a': '1010',
'b': '1011',
'c': '1100',
'd': '1101',
'e': '1110',
'f': '1111',
'A': '1010',
'B': '1011',
'C': '1100',
'D': '1101',
'E': '1110',
'F': '1111'
};
function hexToBinary(s) {
if (Buffer.isBuffer(s)) s = s.toString('hex');
s = s.replace(/^0x/, '');
assert(/^[0-9a-fA-F]+$/.test(s));
var ret = '';
for (var i = 0; i < s.length; i++) ret += lookup[s[i]];
return ret;
}
function hammingDistance(a, b) {
a = hexToBinary(a);
b = hexToBinary(b);
var count = 0;
for (var i = 0; i < a.length; i++) if (a[i] !== b[i]) count++;
return count;
}