-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathjaccard.js
More file actions
91 lines (83 loc) · 1.53 KB
/
jaccard.js
File metadata and controls
91 lines (83 loc) · 1.53 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* jaccard
* <cam@campedersen.com>
*/
var async = require('async');
/*
* Return mutual elements in the input sets
*/
var intersection = function (a, b, c) {
var x = [];
var check = function (e, cb) {
if (~b.indexOf(e)) x.push(e);
if (cb && typeof cb == 'function') cb(null);
};
if (c) {
async.forEach(a, check, function () {
c(null, x);
});
} else {
a.forEach(check);
return x;
}
}
/*
* Return distinct elements from both input sets
*/
var union = function (a, b, c) {
var x = [];
var check = function (e, cb) {
if (!~x.indexOf(e)) x.push(e);
if (cb && typeof cb == 'function') cb(null);
}
if (c) {
var waiting = 2;
var asyncCheck = function () {
if (--waiting == 0) {
c(null, x);
}
}
async.forEach(a, check, asyncCheck);
async.forEach(b, check, asyncCheck);
} else {
a.forEach(check);
b.forEach(check);
return x;
}
}
/*
* Similarity
*/
var index = function (a, b, c) {
if (c) {
async.parallel({
intersection: function (cb) {
intersection(a, b, cb);
},
union: function (cb) {
union(a, b, cb);
}
}, function (err, results) {
c(results.intersection.length / results.union.length);
});
} else {
return intersection(a, b).length / union(a, b).length;
}
}
/*
* Dissimilarity
*/
var distance = function (a, b, c) {
if (c) {
c(1 - index(a, b));
} else {
return 1 - index(a, b);
}
}
/*
* Say cheese
*/
module.exports = {
index: index,
distance: distance
}