a8593b4f4a5a833339fd773955b7ed67375574d721388abf60df53a76bc85e845238443718d9c2dc6878726f775ef69f519477a9589e700fd4a3f74f93de4f 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
  14. tmp = val; val = period; period = tmp;
  15. }
  16. val = typeof val === 'string' ? +val : val;
  17. dur = createDuration(val, period);
  18. addSubtract(this, dur, direction);
  19. return this;
  20. };
  21. }
  22. export function addSubtract (mom, duration, isAdding, updateOffset) {
  23. var milliseconds = duration._milliseconds,
  24. days = absRound(duration._days),
  25. months = absRound(duration._months);
  26. if (!mom.isValid()) {
  27. // No op
  28. return;
  29. }
  30. updateOffset = updateOffset == null ? true : updateOffset;
  31. if (milliseconds) {
  32. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  33. }
  34. if (days) {
  35. set(mom, 'Date', get(mom, 'Date') + days * isAdding);
  36. }
  37. if (months) {
  38. setMonth(mom, get(mom, 'Month') + months * isAdding);
  39. }
  40. if (updateOffset) {
  41. hooks.updateOffset(mom, days || months);
  42. }
  43. }
  44. export var add = createAdder(1, 'add');
  45. export var subtract = createAdder(-1, 'subtract');