interval.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. define([
  2. 'kbn'
  3. ],
  4. function (kbn) {
  5. 'use strict';
  6. /**
  7. * manages the interval logic
  8. * @param {[type]} interval_string An interval string in the format '1m', '1y', etc
  9. */
  10. function Interval(interval_string) {
  11. this.string = interval_string;
  12. var info = kbn.describe_interval(interval_string);
  13. this.type = info.type;
  14. this.ms = info.sec * 1000 * info.count;
  15. // does the length of the interval change based on the current time?
  16. if (this.type === 'y' || this.type === 'M') {
  17. // we will just modify this time object rather that create a new one constantly
  18. this.get = this.get_complex;
  19. this.date = new Date(0);
  20. } else {
  21. this.get = this.get_simple;
  22. }
  23. }
  24. Interval.prototype = {
  25. toString: function () {
  26. return this.string;
  27. },
  28. after: function(current_ms) {
  29. return this.get(current_ms, 1);
  30. },
  31. before: function (current_ms) {
  32. return this.get(current_ms, -1);
  33. },
  34. get_complex: function (current, delta) {
  35. this.date.setTime(current);
  36. switch(this.type) {
  37. case 'M':
  38. this.date.setUTCMonth(this.date.getUTCMonth() + delta);
  39. break;
  40. case 'y':
  41. this.date.setUTCFullYear(this.date.getUTCFullYear() + delta);
  42. break;
  43. }
  44. return this.date.getTime();
  45. },
  46. get_simple: function (current, delta) {
  47. return current + (delta * this.ms);
  48. }
  49. };
  50. return Interval;
  51. });