b8af014e4c1430858b2639d2fe95e4e3922fd93295e22689445f0999cb1c82cc03796b80b8b2cca89370713a6da8ef312cc8ee31fed8b38fcaa0521ccb8ca5 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { get, set } from './get-set';
  2. import { setMonth } from '../units/month';
  3. import { createDuration } from '../duration/create';
  4. import { deprecateSimple } from '../utils/deprecate';
  5. import { hooks } from '../utils/hooks';
  6. import absRound from '../utils/abs-round';
  7. // TODO: remove 'name' arg after deprecation is removed
  8. function createAdder(direction, name) {
  9. return function (val, period) {
  10. var dur, tmp;
  11. //invert the arguments, but complain about it
  12. if (period !== null && !isNaN(+period)) {
  13. deprecateSimple(
  14. name,
  15. 'moment().' +
  16. name +
  17. '(period, number) is deprecated. Please use moment().' +
  18. name +
  19. '(number, period). ' +
  20. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
  21. );
  22. tmp = val;
  23. val = period;
  24. period = tmp;
  25. }
  26. dur = createDuration(val, period);
  27. addSubtract(this, dur, direction);
  28. return this;
  29. };
  30. }
  31. export function addSubtract(mom, duration, isAdding, updateOffset) {
  32. var milliseconds = duration._milliseconds,
  33. days = absRound(duration._days),
  34. months = absRound(duration._months);
  35. if (!mom.isValid()) {
  36. // No op
  37. return;
  38. }
  39. updateOffset = updateOffset == null ? true : updateOffset;
  40. if (months) {
  41. setMonth(mom, get(mom, 'Month') + months * isAdding);
  42. }
  43. if (days) {
  44. set(mom, 'Date', get(mom, 'Date') + days * isAdding);
  45. }
  46. if (milliseconds) {
  47. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  48. }
  49. if (updateOffset) {
  50. hooks.updateOffset(mom, days || months);
  51. }
  52. }
  53. export var add = createAdder(1, 'add'),
  54. subtract = createAdder(-1, 'subtract');