forked from bendrucker/postgres-interval
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
66 lines (60 loc) · 1.68 KB
/
index.js
File metadata and controls
66 lines (60 loc) · 1.68 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
'use strict'
var extend = require('xtend/mutable')
module.exports = PostgresInterval
function PostgresInterval (raw) {
if (!(this instanceof PostgresInterval)) {
return new PostgresInterval(raw)
}
extend(this, parse(raw))
}
var properties = ['seconds', 'minutes', 'hours', 'days', 'months', 'years']
PostgresInterval.prototype.toPostgres = function () {
var filtered = properties.filter(this.hasOwnProperty, this)
if (filtered.length === 0) return '0'
return filtered
.map(function (property) {
return this[property] + ' ' + property
}, this)
.join(' ')
}
var NUMBER = '([+-]?\\d+)'
var YEAR = NUMBER + '\\s+years?'
var MONTH = NUMBER + '\\s+mons?'
var DAY = NUMBER + '\\s+days?'
var TIME = '([+-])?([\\d]*):(\\d\\d):(\\d\\d):?(\\d\\d\\d)?'
var INTERVAL = new RegExp([YEAR, MONTH, DAY, TIME].map(function (regexString) {
return '(' + regexString + ')?'
})
.join('\\s*'))
// Positions of values in regex match
var positions = {
years: 2,
months: 4,
days: 6,
hours: 9,
minutes: 10,
seconds: 11,
milliseconds: 12
}
// We can use negative time
var negatives = ['hours', 'minutes', 'seconds']
function parse (interval) {
if (!interval) return {}
var matches = INTERVAL.exec(interval)
var isNegative = matches[8] === '-'
return Object.keys(positions)
.reduce(function (parsed, property) {
var position = positions[property]
var value = matches[position]
// no empty string
if (!value) return parsed
value = parseInt(value, 10)
// no zeros
if (!value) return parsed
if (isNegative && ~negatives.indexOf(property)) {
value *= -1
}
parsed[property] = value
return parsed
}, {})
}