1. /**
  2. * Deserializes a string of timestamps into an array of Date objects,
  3. * with retry logic for parsing errors.
  4. *
  5. * @param {string} timestampString - A string containing timestamps separated by commas.
  6. * @param {number} maxRetries - The maximum number of retry attempts.
  7. * @returns {Promise<Date[]>} - A promise that resolves with an array of Date objects,
  8. * or rejects if parsing fails after maxRetries attempts.
  9. */
  10. async function deserializeTimestamps(timestampString, maxRetries = 3) {
  11. let attempts = 0;
  12. while (attempts < maxRetries) {
  13. try {
  14. const timestamps = timestampString
  15. .split(',')
  16. .map(timestamp => {
  17. // Attempt to parse the timestamp. Handle different formats.
  18. const parsed = Date.parse(timestamp);
  19. if (!isNaN(parsed)) {
  20. return new Date(parsed);
  21. } else {
  22. // Attempt to parse with ISO 8601 format
  23. const isoParsed = new Date(timestamp);
  24. if (!isNaN(isoParsed.getTime())) {
  25. return isoParsed;
  26. } else {
  27. throw new Error(`Invalid timestamp format: ${timestamp}`);
  28. }
  29. }
  30. });
  31. return timestamps; // Success!
  32. } catch (error) {
  33. attempts++;
  34. console.warn(`Timestamp parsing failed (attempt ${attempts}/${maxRetries}):`, error.message);
  35. if (attempts < maxRetries) {
  36. // Retry after a short delay
  37. await new Promise(resolve => setTimeout(resolve, 100)); // 100ms delay
  38. } else {
  39. return Promise.reject(error); // Rejection after max attempts
  40. }
  41. }
  42. }
  43. }

Add your comment