54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import { HistoryItem } from '@/components/ComparisonHistory';
|
|
|
|
export const saveToHistory = (
|
|
item1: string,
|
|
item2: string,
|
|
description1: string,
|
|
description2: string,
|
|
result: string
|
|
) => {
|
|
try {
|
|
const historyItem: HistoryItem = {
|
|
id: Date.now().toString(),
|
|
item1,
|
|
item2,
|
|
description1,
|
|
description2,
|
|
result,
|
|
timestamp: Date.now(),
|
|
};
|
|
|
|
const existing = localStorage.getItem('comparison-history');
|
|
let history: HistoryItem[] = [];
|
|
|
|
if (existing) {
|
|
history = JSON.parse(existing);
|
|
}
|
|
|
|
// Add new item to the beginning
|
|
history.unshift(historyItem);
|
|
|
|
// Keep only last 50 items
|
|
history = history.slice(0, 50);
|
|
|
|
localStorage.setItem('comparison-history', JSON.stringify(history));
|
|
|
|
// Dispatch custom event for same-page updates
|
|
window.dispatchEvent(new Event('comparison-history-updated'));
|
|
|
|
return historyItem;
|
|
} catch (error) {
|
|
console.error('Error saving to history:', error);
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export const getHistory = (): HistoryItem[] => {
|
|
try {
|
|
const stored = localStorage.getItem('comparison-history');
|
|
return stored ? JSON.parse(stored) : [];
|
|
} catch (error) {
|
|
console.error('Error loading history:', error);
|
|
return [];
|
|
}
|
|
}; |