-
Notifications
You must be signed in to change notification settings - Fork 1
/
exo2.js
102 lines (86 loc) · 2.45 KB
/
exo2.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
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
92
93
94
95
96
97
98
99
100
101
102
// Import MongoDB
const MongoClient = require("mongodb").MongoClient;
// MongoDB localhost url
const url = "mongodb://localhost:27017/";
// Database name
const dbName = "test";
// Create graph
const graph = [
{ _id: "A", value: { linkTo: ["B", "C"], rank: 1 } },
{ _id: "B", value: { linkTo: ["C"], rank: 1 } },
{ _id: "C", value: { linkTo: ["A"], rank: 1 } },
{ _id: "D", value: { linkTo: ["C"], rank: 1 } }
];
// Connect MongoDB
MongoClient.connect(
url,
{ useNewUrlParser: true },
function(err, db) {
// Throw Err if can't connect
if (err) throw err;
// Connect to database
var dataBase = db.db(dbName);
var collection = dataBase.collection("graph");
collection.deleteMany();
collection.removeMany(); //Efface tout (sync)
// Insert collection in mongoDB and use a promise to perform mapReduce
collection.insertMany(graph, { w: 1 }).then(function(result) {
// Map Function (use object "this"
var map = function() {
var linkTo = this.value.linkTo;
var point = this._id;
for (i = 0; i < linkTo.length; i++) {
emit(linkTo[i], this.value.rank / linkTo.length);
}
emit(point, linkTo);
emit(point, 0);
};
// Reduce Function
var reduce = function(key, values) {
var pageRank = 0.0;
var linkTo = [];
// DampingFactor gived in the exercice
const DAMPING_FACTOR = 0.85;
for (i = 0; i < values.length; i++) {
if (values[i] instanceof Array) {
// If the value is an array type (adjacency matrix), it's used to insert in MongoDB
linkTo = values[i];
} else {
// Else, it's the calculed pageRank
pageRank += values[i];
}
}
// New pageRank with the DampingFactor
pageRank = 1 - DAMPING_FACTOR + DAMPING_FACTOR * pageRank;
// Variable used in debug
var result = { linkTo: linkTo, rank: pageRank };
return result;
};
// Iterate the sequence
function iterate(i) {
collection.mapReduce(map, reduce, {out: {replace: "graph"}},
function(err, result) {
// Throw error if error
if (err) throw err;
// Get data from databases to print progress
collection
.find()
.toArray()
.then(function(data) {
console.log("Iterate : " + i);
console.log(data);
if (i < 20) {
iterate(i + 1);
} else {
console.log("End of programm");
db.close();
}
}
);
}
);
}
iterate(0);
});
}
);