使用前缀树/字典树/trie树实现文本高亮

1,048 阅读1分钟

class TrieNode {
  constructor() {
    this.children = new Map();
    this.isEndOfWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
    this.isEndOfWord = false;
  }

  insert(word) {
    let currentNode = this.root;

    for (let i = 0; i < word.length; i++) {
      const char = word[i];
      if (!currentNode.children.has(char)) {
        currentNode.children.set(char, new TrieNode());
      }
      currentNode = currentNode.children.get(char);
    }

    currentNode.isEndOfWord = true;
  }

  highlightText(text, highlightClass = 'highlight') {
    const result = [];
    let currentWord = '';
    let currentNode = this.root;

    for (const char of text) {
      currentWord += char;
      // console.log(currentWord, 'currentWord')
      if (currentNode.children.has(char)) {
        currentNode = currentNode.children.get(char);
        console.log(currentNode, 'currentNode')
        if (currentNode.isEndOfWord) {
          result.push(`<span class="${highlightClass}">${currentWord}</span>`);
          currentWord = '';
          currentNode = this.root;
        }
      } else {
        result.push(currentWord);
        currentWord = '';
        currentNode = this.root;
      }
    }
    if (currentWord) {
      result.push(currentWord);
    }
    return result.join('');
  }
}


// 调用示例
const text = "This is a sample text to highlight certain words.";
const keywords = "words";
let trie = new Trie();
trie.insert(keywords);
console.log(trie.root);
console.log(trie.highlightText(text));