Medium
How to Implement Persistent Watch History in JavaScript Using localStorage
In a video streaming application, you need to implement a feature that tracks a user's watch history. If the user closes the browser and returns later, their progress should be saved. Which of the following implementations correctly persists the watch history?
1class WatchHistory {2 constructor() {3 this.history = [];4 }56 addToHistory(videoId, timestamp) {7 // Implementation A8 const entry = {9 videoId,10 timestamp,11 lastWatched: new Date().toISOString()12 };13 this.history.push(entry);14 localStorage.setItem('watchHistory', JSON.stringify(this.history));15 }1617 getHistory() {18 return JSON.parse(localStorage.getItem('watchHistory')) || [];19 }2021 updateProgress(videoId, newTimestamp) {22 this.history = this.getHistory();23 const videoIndex = this.history.findIndex(v => v.videoId === videoId);24 if (videoIndex !== -1) {25 this.history[videoIndex].timestamp = newTimestamp;26 this.history[videoIndex].lastWatched = new Date().toISOString();27 localStorage.setItem('watchHistory', JSON.stringify(this.history));28 }29 }30}