Есть ли способ хранить Trie в расширении Chrome с глубоко вложенным корнем?Javascript

Форум по Javascript
Ответить
Anonymous
 Есть ли способ хранить Trie в расширении Chrome с глубоко вложенным корнем?

Сообщение 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;
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
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»