Skip to content

Commit 52dfb13

Browse files
authored
fix: Add plugin objectSupport (#887)
1 parent 058d624 commit 52dfb13

File tree

3 files changed

+419
-0
lines changed

3 files changed

+419
-0
lines changed

src/plugin/objectSupport/index.js

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
export default (o, c) => {
2+
const proto = c.prototype
3+
const isObject = obj => !(obj instanceof Date) && !(obj instanceof Array) && obj instanceof Object
4+
const prettyUnit = (u) => {
5+
const unit = proto.$utils().p(u)
6+
return unit === 'date' ? 'day' : unit
7+
}
8+
const parseDate = (cfg) => {
9+
const { date, utc } = cfg
10+
const $d = {}
11+
if (isObject(date)) {
12+
Object.keys(date).forEach((k) => {
13+
$d[prettyUnit(k)] = date[k]
14+
})
15+
const y = $d.year || 1970
16+
const M = $d.month - 1 || 0
17+
const d = $d.day || 1
18+
const h = $d.hour || 0
19+
const m = $d.minute || 0
20+
const s = $d.second || 0
21+
const ms = $d.millisecond || 0
22+
if (utc) {
23+
return new Date(Date.UTC(y, M, d, h, m, s, ms))
24+
}
25+
return new Date(y, M, d, h, m, s, ms)
26+
}
27+
return date
28+
}
29+
30+
const oldParse = proto.parse
31+
proto.parse = function (cfg) {
32+
cfg.date = parseDate.bind(this)(cfg)
33+
oldParse.bind(this)(cfg)
34+
}
35+
36+
const oldSet = proto.set
37+
const oldAdd = proto.add
38+
39+
const callObject = function (call, argument, string, offset = 1) {
40+
if (argument instanceof Object) {
41+
const keys = Object.keys(argument)
42+
let chain = this
43+
keys.forEach((key) => {
44+
chain = call.bind(chain)(argument[key] * offset, key)
45+
})
46+
return chain
47+
}
48+
return call.bind(this)(argument * offset, string)
49+
}
50+
51+
proto.set = function (string, int) {
52+
int = int === undefined ? string : int
53+
return callObject.bind(this)(function (i, s) {
54+
return oldSet.bind(this)(s, i)
55+
}, int, string)
56+
}
57+
proto.add = function (number, string) {
58+
return callObject.bind(this)(oldAdd, number, string)
59+
}
60+
proto.subtract = function (number, string) {
61+
return callObject.bind(this)(oldAdd, number, string, -1)
62+
}
63+
}

0 commit comments

Comments
 (0)