UNPKG

2.52 kBJavaScriptView Raw
1export default (function (o, c, dayjs) {
2 var proto = c.prototype;
3
4 var isObject = function isObject(obj) {
5 return obj !== null && !(obj instanceof Date) && !(obj instanceof Array) && !proto.$utils().u(obj) && obj.constructor.name === 'Object';
6 };
7
8 var prettyUnit = function prettyUnit(u) {
9 var unit = proto.$utils().p(u);
10 return unit === 'date' ? 'day' : unit;
11 };
12
13 var parseDate = function parseDate(cfg) {
14 var date = cfg.date,
15 utc = cfg.utc;
16 var $d = {};
17
18 if (isObject(date)) {
19 if (!Object.keys(date).length) {
20 return new Date();
21 }
22
23 var now = utc ? dayjs.utc() : dayjs();
24 Object.keys(date).forEach(function (k) {
25 $d[prettyUnit(k)] = date[k];
26 });
27 var d = $d.day || (!$d.year && !($d.month >= 0) ? now.date() : 1);
28 var y = $d.year || now.year();
29 var M = $d.month >= 0 ? $d.month : !$d.year && !$d.day ? now.month() : 0; // eslint-disable-line no-nested-ternary,max-len
30
31 var h = $d.hour || 0;
32 var m = $d.minute || 0;
33 var s = $d.second || 0;
34 var ms = $d.millisecond || 0;
35
36 if (utc) {
37 return new Date(Date.UTC(y, M, d, h, m, s, ms));
38 }
39
40 return new Date(y, M, d, h, m, s, ms);
41 }
42
43 return date;
44 };
45
46 var oldParse = proto.parse;
47
48 proto.parse = function (cfg) {
49 cfg.date = parseDate.bind(this)(cfg);
50 oldParse.bind(this)(cfg);
51 };
52
53 var oldSet = proto.set;
54 var oldAdd = proto.add;
55 var oldSubtract = proto.subtract;
56
57 var callObject = function callObject(call, argument, string, offset) {
58 if (offset === void 0) {
59 offset = 1;
60 }
61
62 var keys = Object.keys(argument);
63 var chain = this;
64 keys.forEach(function (key) {
65 chain = call.bind(chain)(argument[key] * offset, key);
66 });
67 return chain;
68 };
69
70 proto.set = function (unit, value) {
71 value = value === undefined ? unit : value;
72
73 if (unit.constructor.name === 'Object') {
74 return callObject.bind(this)(function (i, s) {
75 return oldSet.bind(this)(s, i);
76 }, value, unit);
77 }
78
79 return oldSet.bind(this)(unit, value);
80 };
81
82 proto.add = function (value, unit) {
83 if (value.constructor.name === 'Object') {
84 return callObject.bind(this)(oldAdd, value, unit);
85 }
86
87 return oldAdd.bind(this)(value, unit);
88 };
89
90 proto.subtract = function (value, unit) {
91 if (value.constructor.name === 'Object') {
92 return callObject.bind(this)(oldAdd, value, unit, -1);
93 }
94
95 return oldSubtract.bind(this)(value, unit);
96 };
97});
\No newline at end of file