javascript中的哈希表topicData对象,以使主题与文本

时间:2018-05-29 04:48:04

标签: javascript data-structures

我在以下代码中遇到了性能问题,因为我必须与gmail邮件中的文本匹配的主题数量超过1000,因为它会导致我的Gmail崩溃或速度变慢。我正在考虑使用哈希表,但我不确定如何正确使用它,我如何检查node.textContent。这是我所做的,它没有哈希表。

var topicData = [
    {
        id: 1,
        name: 'Courses'
    },
    {
        id: 2,
        name: 'miss'
    },
    {
        id: 3,
        name: 'out'
    },
    {
        id: 4,
        name: 'your'
    },
    {
        id: 5,
        name: 'savings'
    },
    {
        id: 6,
        name: 'and'
    }
];

function fetchTopics() {
    // const apiUrl = `http://localhost:3020/v2/emails`;
    // const headers = new Headers();
    // headers.append('Content-Type', 'application/json');
    return topicData.map(datum => {
        return searchPage(datum.name);
    });
    // fetch(apiUrl, {
    //  method: 'GET',
    //  headers
    // })
    //  .then(function(response) {
    //      return response.json();
    //  })
    //  .then(function(data) {
    //      topicData.map(datum => searchPage(data.name));
    //  })
    //  .catch(function(err) {
    //      console.log('err', err);
    //  });
}

/*  the searchPage function takes an argument which is going
to set the variable re. Then iterate through topic array and call the searchPage function
for each value inside it while passing that value to the function
*/
function searchPage(topic) {
    console.log('topic', topic);
    var re = new RegExp(topic, 'g'); // example regex that the function will use for search
    var regs;

    var walker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_TEXT,
        function(node) {
            if ((regs = re.exec(node.textContent))) {
                if (!node.parentNode.classList.contains('highlighted_text')) {
                    var match = document.createElement('A');
                    match.appendChild(document.createTextNode(regs[0]));
                    match.href = `https://app.com/CustomTopic/${
                        regs[0]
                    }`;
                    match.classList.add('highlighted_text');

                    var after = node.splitText(regs.index);
                    after.nodeValue = after.nodeValue.substring(regs[0].length);
                    node.parentNode.insertBefore(match, after);
                }
            }
            return NodeFilter.FILTER_SKIP;
        },
        false
    );

    walker.nextNode();
}

// Run when the whole document loads
$(window).bind('load', function() {
    document.addEventListener('click', init);
    fetchTopics();
});

$(window).on('hashchange', function() {
    fetchTopics();
});

0 个答案:

没有答案