/**
* Deserializes a string of timestamps into an array of Date objects,
* with retry logic for parsing errors.
*
* @param {string} timestampString - A string containing timestamps separated by commas.
* @param {number} maxRetries - The maximum number of retry attempts.
* @returns {Promise<Date[]>} - A promise that resolves with an array of Date objects,
* or rejects if parsing fails after maxRetries attempts.
*/
async function deserializeTimestamps(timestampString, maxRetries = 3) {
let attempts = 0;
while (attempts < maxRetries) {
try {
const timestamps = timestampString
.split(',')
.map(timestamp => {
// Attempt to parse the timestamp. Handle different formats.
const parsed = Date.parse(timestamp);
if (!isNaN(parsed)) {
return new Date(parsed);
} else {
// Attempt to parse with ISO 8601 format
const isoParsed = new Date(timestamp);
if (!isNaN(isoParsed.getTime())) {
return isoParsed;
} else {
throw new Error(`Invalid timestamp format: ${timestamp}`);
}
}
});
return timestamps; // Success!
} catch (error) {
attempts++;
console.warn(`Timestamp parsing failed (attempt ${attempts}/${maxRetries}):`, error.message);
if (attempts < maxRetries) {
// Retry after a short delay
await new Promise(resolve => setTimeout(resolve, 100)); // 100ms delay
} else {
return Promise.reject(error); // Rejection after max attempts
}
}
}
}
Add your comment