index.js 2.5 KB

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