-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
40 lines (31 loc) · 1.03 KB
/
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
var groupByTime
, groupBy = require('lodash.groupby')
function getMonday(d) {
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1) // adjust when day is sunday
return new Date(d.setDate(diff))
}
function groupByTime (arr, key, group) {
var groupings = {
day: function (obj) {
var date = new Date(obj[key])
date.setHours(0, 0, 0, 0)
return date.valueOf()
}
, week: function (obj) {
var date = new Date(obj[key])
date.setHours(0, 0, 0, 0)
return getMonday(date).valueOf()
}
, month: function (obj) {
var date = new Date(obj[key])
return new Date(date.getFullYear(), date.getMonth(), 1).valueOf()
}
}
if (!group) group == 'day'
return groupBy(arr, groupings[group])
}
groupByTime.byDay = function (arr, key) { return groupByTime(arr, key, 'day') }
groupByTime.byWeek = function (arr, key) { return groupByTime(arr, key, 'week') }
groupByTime.byMonth = function (arr, key) { return groupByTime(arr, key, 'month') }
module.exports = groupByTime