-
Notifications
You must be signed in to change notification settings - Fork 2
/
walker.js
120 lines (109 loc) · 2.69 KB
/
walker.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
var net = require('net');
var Walker = module.exports = function(params) {
if (!(this instanceof Walker)) return new Walker(params);
this.params = params;
this._interval = 100000;
this.slept = false;
this.builders = [];
this.cumProb = 0;
return this;
};
Walker.builder = function(name) {
var args = Array.prototype.slice.call(arguments, 1);
if (!builder[name]) {
throw new Error('cannot find builder ' + name);
}
return builder[name].apply(null, args);
};
Walker.prototype.walk = function(port, host) {
var that = this,
socket = new net.Socket();
if (this.slept) {
return this;
}
this.slept = true;
socket.on('connect', function() {
setInterval(function() {
var builder = that.selectBuilder();
if (!builder) return;
socket.write(JSON.stringify(builder(that)) + "\0");
}, that._interval);
});
socket.on('error', function() {
console.log('error');
});
socket.connect(port, host || 'localhost');
return this;
};
Walker.prototype.interval = function(n) {
this._interval = n;
return this;
};
Walker.prototype.use = function(builder, prob) {
var sum = this.cumProb + prob;
if (sum > 1) {
throw new Error('error: sum of probability should not exceed 1.');
}
this.builders.push({ range: [this.cumProb, sum], builder: builder });
this.cumProb = sum;
return this;
};
Walker.prototype.selectBuilder = function() {
var rand = Math.random(),
builderToUse;
this.builders.some(function(builder) {
var match = rand < builder.range[1];
if (match) {
builderToUse = builder.builder;
}
return match;
});
return builderToUse;
};
Walker.prototype.after = function(lat, lon) {
return this;
};
var builder = {};
builder.location = function() {
var latitude = arguments[0] || 0,
longitude = arguments[1] || 0;
return function(walker) {
var data = {};
for (var key in walker.params) {
data[key] = walker.params[key];
}
data.type = 'location';
latitude = latitude += rand(0.0001);
longitude = longitude += rand(0.0001);
data.data = {
latitude: latitude,
longitude: longitude,
timestamp: new Date().getTime()
};
return data;
};
};
builder.heading = function() {
var heading = 0;
return function(walker) {
var data = {},
val = rand(10);
heading += val;
if (heading > 360) {
heading -= 360;
}
for (var key in walker.params) {
data[key] = walker.params[key];
}
data.type = 'heading';
data.data = {
trueHeading: heading,
timestamp: new Date().getTime()
};
return data;
};
};
function rand(width, mean) {
mean = mean || 0;
return Math.random() * width * 2 - width + mean;
}