All files memory.js

100% Statements 56/56
100% Branches 10/10
100% Functions 5/5
100% Lines 56/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 25x 25x 25x 1x 1x 1x 1x 1x 42x 42x 1x 1x 1x 1x 20x 19x 20x 1x 1x 1x 1x 20x 1x 1x 1x 1x 1x 14x 2x 2x 14x 14x 1x 1x 1x 1x 26x 26x 1x 1x 1x  
"use strict";
 
import Conversation from "./conversation.js";
 
// Memory class to manage conversations for different players.
// Because a single Mineflayer bot can interact with multiple players,
// a conversation with each player has its own history and context.
// TODO: Consider adding configurable memory expiration.
// E.g. if a player hasn't interacted for a while, their memory could be cleared.
// This could be implemented with a timestamp for each conversation.
class Memory {
  // Initializes a new Memory instance.
  // The historySize parameter limits the number of messages stored per player conversation.
  // When the limit is exceeded, the oldest message is removed.
  constructor(historySize) {
    this.conversations = {};
    this.historySize = historySize || 20;
  }
 
  // Check if there's any memory of a conversation with a specific player.
  // Returns true if the player exists in memory, false otherwise.
  // This is useful for checking if a player has an ongoing conversation.
  exists(player) {
    return player in this.conversations;
  }
 
  // Initialize a conversation with a specific player.
  // If the player already exists, it does nothing and logs a warning.
  initialize(player) {
    if (!this.exists(player)) {
      this.conversations[player] = new Conversation(this.historySize);
    } else {
      console.info(
        `Memory for player ${player} already exists. Nothing to initialize.`,
      );
    }
  }
 
  // Retrieve the conversation history for a specific player.
  // If the player does not exist in memory, it initializes a new conversation.
  // This ensures that the conversation can be used immediately without checking existence.
  retrieve(player) {
    if (!this.exists(player)) {
      this.initialize(player);
    }
    return this.conversations[player];
  }
 
  // Register a new message in the conversation for a specific player.
  // This method adds a message to the player's conversation history.
  register(player, message) {
    this.conversations[player].addMessage(message);
  }
}
 
export { Memory as default };