2021-07-19 20:20:49 +02:00
|
|
|
interface ListHistory {
|
|
|
|
id: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getHistory(): ListHistory[] {
|
2021-07-06 22:22:57 +02:00
|
|
|
const savedHistory = localStorage.getItem('listHistory')
|
|
|
|
if (savedHistory === null) {
|
|
|
|
return []
|
|
|
|
}
|
|
|
|
|
|
|
|
return JSON.parse(savedHistory)
|
|
|
|
}
|
|
|
|
|
2021-07-20 18:03:38 +02:00
|
|
|
function saveHistory(history: ListHistory[]) {
|
|
|
|
if (history.length === 0) {
|
|
|
|
localStorage.removeItem('listHistory')
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
localStorage.setItem('listHistory', JSON.stringify(history))
|
|
|
|
}
|
2021-07-06 22:22:57 +02:00
|
|
|
|
2021-07-20 18:03:38 +02:00
|
|
|
export function saveListToHistory(list: ListHistory) {
|
|
|
|
const history: ListHistory[] = getHistory()
|
2021-07-17 19:10:05 +02:00
|
|
|
|
2021-07-06 22:22:57 +02:00
|
|
|
// Remove the element if it already exists in history, preventing duplicates and essentially moving it to the beginning
|
2021-07-19 20:20:49 +02:00
|
|
|
history.forEach((l, i) => {
|
|
|
|
if (l.id === list.id) {
|
2021-07-06 22:22:57 +02:00
|
|
|
history.splice(i, 1)
|
|
|
|
}
|
2021-07-19 20:20:49 +02:00
|
|
|
})
|
2021-07-06 22:22:57 +02:00
|
|
|
|
2021-07-17 19:10:05 +02:00
|
|
|
// Add the new list to the beginning of the list
|
2021-07-06 22:22:57 +02:00
|
|
|
history.unshift(list)
|
|
|
|
|
|
|
|
if (history.length > 5) {
|
|
|
|
history.pop()
|
|
|
|
}
|
2021-07-20 18:03:38 +02:00
|
|
|
saveHistory(history)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function removeListFromHistory(list: ListHistory) {
|
|
|
|
const history: ListHistory[] = getHistory()
|
|
|
|
|
|
|
|
history.forEach((l, i) => {
|
|
|
|
if (l.id === list.id) {
|
|
|
|
history.splice(i, 1)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
saveHistory(history)
|
2021-07-06 22:22:57 +02:00
|
|
|
}
|