datemath.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. ///<reference path="../../headers/common.d.ts" />
  2. import _ from 'lodash';
  3. import moment from 'moment';
  4. var units = ['y', 'M', 'w', 'd', 'h', 'm', 's'];
  5. export function parse(text, roundUp?) {
  6. if (!text) { return undefined; }
  7. if (moment.isMoment(text)) { return text; }
  8. if (_.isDate(text)) { return moment(text); }
  9. var time;
  10. var mathString = '';
  11. var index;
  12. var parseString;
  13. if (text.substring(0, 3) === 'now') {
  14. time = moment();
  15. mathString = text.substring('now'.length);
  16. } else {
  17. index = text.indexOf('||');
  18. if (index === -1) {
  19. parseString = text;
  20. mathString = ''; // nothing else
  21. } else {
  22. parseString = text.substring(0, index);
  23. mathString = text.substring(index + 2);
  24. }
  25. // We're going to just require ISO8601 timestamps, k?
  26. time = moment(parseString, moment.ISO_8601);
  27. }
  28. if (!mathString.length) {
  29. return time;
  30. }
  31. return parseDateMath(mathString, time, roundUp);
  32. }
  33. export function isValid(text) {
  34. var date = parse(text);
  35. if (!date) {
  36. return false;
  37. }
  38. if (moment.isMoment(date)) {
  39. return date.isValid();
  40. }
  41. return false;
  42. }
  43. export function parseDateMath(mathString, time, roundUp?) {
  44. var dateTime = time;
  45. var i = 0;
  46. var len = mathString.length;
  47. while (i < len) {
  48. var c = mathString.charAt(i++);
  49. var type;
  50. var num;
  51. var unit;
  52. if (c === '/') {
  53. type = 0;
  54. } else if (c === '+') {
  55. type = 1;
  56. } else if (c === '-') {
  57. type = 2;
  58. } else {
  59. return undefined;
  60. }
  61. if (isNaN(mathString.charAt(i))) {
  62. num = 1;
  63. } else if (mathString.length === 2) {
  64. num = mathString.charAt(i);
  65. } else {
  66. var numFrom = i;
  67. while (!isNaN(mathString.charAt(i))) {
  68. i++;
  69. if (i > 10) { return undefined; }
  70. }
  71. num = parseInt(mathString.substring(numFrom, i), 10);
  72. }
  73. if (type === 0) {
  74. // rounding is only allowed on whole, single, units (eg M or 1M, not 0.5M or 2M)
  75. if (num !== 1) {
  76. return undefined;
  77. }
  78. }
  79. unit = mathString.charAt(i++);
  80. if (!_.contains(units, unit)) {
  81. return undefined;
  82. } else {
  83. if (type === 0) {
  84. if (roundUp) {
  85. dateTime.endOf(unit);
  86. } else {
  87. dateTime.startOf(unit);
  88. }
  89. } else if (type === 1) {
  90. dateTime.add(num, unit);
  91. } else if (type === 2) {
  92. dateTime.subtract(num, unit);
  93. }
  94. }
  95. }
  96. return dateTime;
  97. }