import path from 'path'; import fs from 'fs'; export default class HistoryFile { constructor(fileName) { this.path = path.join(process.cwd(), fileName); this.history = []; this.load(); } /** * Writes history to file * @returns {boolean} true if successful, false otherwise */ writeToFile() { try { fs.writeFileSync(this.path, JSON.stringify(this.history, null, 2)); return true; } catch (err) { console.error(`Failed to write data to history file: ${err.message}`); return false; } } /** * Reads history file, and returns it as JSON * @returns {array} */ readFromFile() { try { const raw = fs.readFileSync(this.path, 'utf-8'); return JSON.parse(raw); } catch (err) { console.warn(`Failed at reading history, using empty history: ${err.message}`); return []; } } /** * Loads history file, if it exists * If not, creates empty file */ load() { if (fs.existsSync(this.path)) { // Read file, and update this.history const data = this.readFromFile(); this.history = data; } else { // Create empty history file, if doesn't exist this.writeToFile(); } } /** * Saves most recent 15 entries to history file */ save() { // If there's more than 15 entries, we need to save only most recent 15 ones if (this.history.length > 15) { this.history = this.history.slice(this.history.length - 15); } // Write to history file this.writeToFile(); } /** * Appends new entry to history file * Returns most recent entry * @param {number} number * @returns {object} */ append(number) { const data = { number, timestamp: Date.now() }; // Push new entry to history this.history.push(data); // Save history file, and keep only 15 entries this.save(); // Return most recent entry return data; } }