This repository has been archived by the owner on Apr 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EarthquakeCounter.js
87 lines (71 loc) · 1.87 KB
/
EarthquakeCounter.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
(function () {
var request = require('request');
var _ = require('lodash');
var REFRESH_RATE = 60 * 60 * 1000; // Once every 60 minutes
function earthquakeCounter(options) {
var me = {
count: {},
load: function () {
var resOptions = {
url: 'http://earthquake.usgs.gov/fdsnws/event/1/query',
qs: _.extend({
format: 'geojson',
starttime: me.startTime,
endtime: me.endTime
}, options),
json: true
};
request.get(resOptions, function (error, response, body) {
me.count = handleEarthquakes(body);
me.afterLoad();
console.log(me.count);
});
},
afterLoad: options.afterLoad || function () {}
};
Object.defineProperties(me, {
startTime: {
enumerate: true,
get: function () {
var now = new Date();
return now.getFullYear() + '-' + bufferString(now.getMonth() + 1, 2) + '-01';
}
},
endTime: {
enumerate: true,
get: function () {
var now = new Date();
return now.getFullYear() + '-' + bufferString(now.getMonth() + 1, 2) + '-' + bufferString(now.getDate() + 1, 2);
}
}
});
var refreshTime = options.refreshTime || REFRESH_RATE;
function bufferString(string, length) {
string = string.toString();
if (string.length < length) {
return bufferString('0' + string, length);
}
else {
return string;
}
}
function handleEarthquakes(earthquakes) {
var dict = {};
_.forEach(earthquakes.features, function (earthquake) {
var mag = Math.round(earthquake.properties.mag);
if (!dict[mag]) {
dict[mag] = 0;
}
dict[mag]++;
});
dict.totalCount = earthquakes.metadata.count;
return dict;
}
me.load();
setInterval(function () {
me.load();
}, refreshTime);
return me;
}
module.exports = earthquakeCounter;
})();