Medium
How to Create a Time Ago Formatter for Real-Time Chat Messages in JavaScript
Your team is developing a real-time chat application where messages need to appear with time markers like 'Just now', '5 minutes ago', etc. What's happening in this utility function?
1class TimeFormatter {2 constructor() {3 this.intervals = {4 year: 31536000,5 month: 2592000,6 week: 604800,7 day: 86400,8 hour: 3600,9 minute: 60,10 second: 111 };12 this.messages = new Map();13 }1415 formatMessage(timestamp) {16 const seconds = Math.floor((Date.now() - timestamp) / 1000);1718 for (let [unit, secondsInUnit] of Object.entries(this.intervals)) {19 const interval = Math.floor(seconds / secondsInUnit);2021 if (interval >= 1) {22 this.messages.set(timestamp, `${interval} ${unit}${interval !== 1 ? 's' : ''} ago`);23 return this.messages.get(timestamp);24 }25 }2627 return 'Just now';28 }29}3031const formatter = new TimeFormatter();32console.log(formatter.formatMessage(Date.now() - 7200000));