Modify the below code to provide only single word meanings or synonyms seperated by…
- User
Modify the below code to provide only single word meanings or synonyms seperated by semicolons if no matches are found in the four words below:
// content.js
// Cache to store fetched data and prevent redundant API calls const dataCache = {};
// Variable to keep track of the currently hovered word let currentWord = null;
// Variable to keep the tooltip element let tooltip = null;
// Listen for mouseover events document.addEventListener('mouseover', handleMouseOver);
// Listen for mouseout events to remove tooltip document.addEventListener('mouseout', handleMouseOut);
// Function to handle mouseover events function handleMouseOver(event) { const result = getWordUnderCursor(event); if (!result) return;
const word = result.word; const range = result.range;
// If there's a word and it's different from the current word if (word && word !== currentWord) { currentWord = word;
// Get the next four words const nextWords = getNextWords(range, 4); // Check if data is already cached if (dataCache[word]) { processSimilarWordsData(event.pageX, event.pageY, word, nextWords, dataCache[word]); } else { // Fetch similar words for the hovered word fetchSimilarWords(word) .then(similarWordsData => { dataCache[word] = similarWordsData; // Cache the data processSimilarWordsData(event.pageX, event.pageY, word, nextWords, similarWordsData); }) .catch(error => { console.error('Error:', error); }); }} }
// Function to process similar words data function processSimilarWordsData(x, y, word, nextWords, similarWordsData) { const similarWords = similarWordsData.map(obj => obj.word.toLowerCase());
// For each of the four words, check if it appears in the similar words list let closestWord = null; let highestScore = -Infinity;
nextWords.forEach(nextWord => { const index = similarWords.indexOf(nextWord.toLowerCase()); if (index !== -1) { // Get the score from similarWordsData const score = similarWordsData[index].score; if (score > highestScore) { highestScore = score; closestWord = nextWord; } } });
if (closestWord) { showTooltip(x, y,
Closest word: ${closestWord}); } else { // Fetch synonyms or definitions for the hovered word fetchDefinitions(word) .then(definitions => { let content = ''; if (definitions.length > 0) { content =Synonyms or Meanings of "${word}":\n- ${definitions.join('\n- ')}; } else { content =No synonyms or meanings found for "${word}".; } showTooltip(x, y, content); }) .catch(error => { console.error('Error fetching definitions:', error); showTooltip(x, y,No similar words found among the next four words.\nNo definitions found for "${word}".); }); } }// Function to handle mouseout events function handleMouseOut(event) { const relatedTarget = event.relatedTarget;
- Assistant