Medium
In a social media app, you need to implement a feature that shows how long ago a post was created (e.g., "2 hours ago", "3 days ago"). What's wrong with this implementation?
1function getTimeAgo(timestamp) {2 const seconds = Math.floor((Date.now() - timestamp) / 1000);3 const minutes = Math.floor(seconds / 60);4 const hours = Math.floor(minutes / 60);5 const days = Math.floor(hours / 24);6 const months = Math.floor(days / 30);7 const years = Math.floor(months / 12);89 const formatPlural = (num, unit) =>10 `${num} ${unit}${num === 1 ? '' : 's'} ago`;1112 if (years > 0) return formatPlural(years, 'year');13 if (months > 0) return formatPlural(months, 'month');14 if (days > 0) return formatPlural(days, 'day');15 if (hours > 0) return formatPlural(hours, 'hour');16 if (minutes > 0) return formatPlural(minutes, 'minute');17 return 'Just now';18}1920// Usage21const PostTimestamp = ({ timestamp }) => {22 const [timeAgo, setTimeAgo] = useState(getTimeAgo(timestamp));2324 useEffect(() => {25 const timer = setInterval(() => {26 setTimeAgo(getTimeAgo(timestamp));27 }, 60000);2829 return () => clearInterval(timer);30 }, [timestamp]);3132 return <span>{timeAgo}</span>;33};