Я пытаюсь создать расширение Chrome, в котором пользователь добавляет текстовые фрагменты в расширение, тогда, когда он вводит в TextARea/Input/AtteDeedtable/Rich-Text Editors, выпадает с выбором с автозаполненными предложениями.
Я использую трип Если я использую json.stringify. < /p>
// In content.js
class TrieNode {
constructor() {
this.children = {};
this.wordEnd = false;
}
}
class Trie {
constructor(tree) {
this.root = tree || new TrieNode();
};
insert(key) {
let node = this.root;
for (let i = 0; i < key.length; i++) {
const char = key;
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.wordEnd = true;
}
search(key) {
let node = this.root;
for (let i = 0; i < key.length; i++) {
const char = key;
if (!node.children[char]) {
return false
}
node = node.children[char];
}
return node.wordEnd
}
delete(key) {
const deleteRecursively = (node, key, depth) => {
if (!node) {
return false;
}
// If we have reached the end of the key
if (depth === key.length) {
// This node is no longer the end of the word
if (node.wordEnd) {
node.wordEnd = false;
}
// If the node has no children, it can be deleted
return Object.keys(node.children).length === 0;
}
const char = key[depth];
if (deleteRecursively(node.children[char], key, depth + 1)) {
// Delete the child node
delete node.children[char];
// Return true if the current node has no children and is not the end of another word
return Object.keys(node.children).length === 0 && !node.wordEnd;
}
return false;
};
deleteRecursively(this.root, key, 0);
}
autoComplete(prefix) {
// go to the last node of the prefix
let node = this.root;
let suggestions = [];
for (let i = 0; i < prefix.length; i++) {
const char = prefix;
if (!node.children[char]) {
// if char in prefix does not exist in Trie
return suggestions
}
node = node.children[char];
}
const keys = Object.keys(node.children);
if (node.wordEnd && keys.length === 0) {
// if the prefix is a complete string in the Trie and has no children
return false;
}
this._dfs(node, prefix, suggestions);
return suggestions
}
startsWith(prefix) {
let node = this.root;
for (let i = 0; i < prefix.length; i++) {
const char = prefix;
if (!node.children[char]) {
// if char in prefix does not exist in Trie
return false;
}
node = node.children[char];
}
return true;
}
_dfs(node, prefix, suggestions) {
if (node.wordEnd) {
// if the prefix is a complete string in the Trie
suggestions.push(prefix)
}
for (let char in node.children) {
this._dfs(node.children[char], prefix + char, suggestions)
}
}
};
// method that inserts words into Trie and stores root
trieInsert(key) {
this.trie.insert(key);
chrome.runtime.sendMessage({
action: "saveTrie",
data: this.trie.root
});
}
// method that retrieves the root from storage
async _loadTrieFromStorage() {
return new Promise((resolve) => {
chrome.runtime.sendMessage({ action: "getTrie" }, (response) => {
if (response && response.data) {
this.trie = new Trie(response.data);
} else {
this.trie = new Trie();
}
resolve();
});
});
}
< /code>
// In background.js
if (request.action === "getTrie") {
chrome.storage.local.get("trie", (data) => {
sendResponse({data: data.trie});
});
return true; // Keep message channel open for async response
}
if (request.action === "saveTrie") {
chrome.storage.local.set({"trie": request.data});
sendResponse({success: true});
return true;
}
< /code>
My question is, is it possible to store a deeply nested trie in storage in chrome extensions? or should I re-insert each string everytime the content.js is loaded in pages and iframes, or should I be using Trie at all in this case?
A live example reproducing the issue
Подробнее здесь: https://stackoverflow.com/questions/796 ... ested-root
Есть ли способ хранить Trie в расширении Chrome с глубоко вложенным корнем? ⇐ Javascript
Форум по Javascript
1749042732
Anonymous
Я пытаюсь создать расширение Chrome, в котором пользователь добавляет текстовые фрагменты в расширение, тогда, когда он вводит в TextARea/Input/AtteDeedtable/Rich-Text Editors, выпадает с выбором с автозаполненными предложениями.
Я использую трип Если я использую json.stringify. < /p>
// In content.js
class TrieNode {
constructor() {
this.children = {};
this.wordEnd = false;
}
}
class Trie {
constructor(tree) {
this.root = tree || new TrieNode();
};
insert(key) {
let node = this.root;
for (let i = 0; i < key.length; i++) {
const char = key[i];
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.wordEnd = true;
}
search(key) {
let node = this.root;
for (let i = 0; i < key.length; i++) {
const char = key[i];
if (!node.children[char]) {
return false
}
node = node.children[char];
}
return node.wordEnd
}
delete(key) {
const deleteRecursively = (node, key, depth) => {
if (!node) {
return false;
}
// If we have reached the end of the key
if (depth === key.length) {
// This node is no longer the end of the word
if (node.wordEnd) {
node.wordEnd = false;
}
// If the node has no children, it can be deleted
return Object.keys(node.children).length === 0;
}
const char = key[depth];
if (deleteRecursively(node.children[char], key, depth + 1)) {
// Delete the child node
delete node.children[char];
// Return true if the current node has no children and is not the end of another word
return Object.keys(node.children).length === 0 && !node.wordEnd;
}
return false;
};
deleteRecursively(this.root, key, 0);
}
autoComplete(prefix) {
// go to the last node of the prefix
let node = this.root;
let suggestions = [];
for (let i = 0; i < prefix.length; i++) {
const char = prefix[i];
if (!node.children[char]) {
// if char in prefix does not exist in Trie
return suggestions
}
node = node.children[char];
}
const keys = Object.keys(node.children);
if (node.wordEnd && keys.length === 0) {
// if the prefix is a complete string in the Trie and has no children
return false;
}
this._dfs(node, prefix, suggestions);
return suggestions
}
startsWith(prefix) {
let node = this.root;
for (let i = 0; i < prefix.length; i++) {
const char = prefix[i];
if (!node.children[char]) {
// if char in prefix does not exist in Trie
return false;
}
node = node.children[char];
}
return true;
}
_dfs(node, prefix, suggestions) {
if (node.wordEnd) {
// if the prefix is a complete string in the Trie
suggestions.push(prefix)
}
for (let char in node.children) {
this._dfs(node.children[char], prefix + char, suggestions)
}
}
};
// method that inserts words into Trie and stores root
trieInsert(key) {
this.trie.insert(key);
chrome.runtime.sendMessage({
action: "saveTrie",
data: this.trie.root
});
}
// method that retrieves the root from storage
async _loadTrieFromStorage() {
return new Promise((resolve) => {
chrome.runtime.sendMessage({ action: "getTrie" }, (response) => {
if (response && response.data) {
this.trie = new Trie(response.data);
} else {
this.trie = new Trie();
}
resolve();
});
});
}
< /code>
// In background.js
if (request.action === "getTrie") {
chrome.storage.local.get("trie", (data) => {
sendResponse({data: data.trie});
});
return true; // Keep message channel open for async response
}
if (request.action === "saveTrie") {
chrome.storage.local.set({"trie": request.data});
sendResponse({success: true});
return true;
}
< /code>
My question is, is it possible to store a deeply nested trie in storage in chrome extensions? or should I re-insert each string everytime the content.js is loaded in pages and iframes, or should I be using Trie at all in this case?
A live example reproducing the issue
Подробнее здесь: [url]https://stackoverflow.com/questions/79652523/is-there-a-way-to-store-trie-in-chrome-extension-with-a-deeply-nested-root[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия