хэш-таблица topicData объект в javascript, чтобы сопоставить тему с текстом - PullRequest
0 голосов
/ 29 мая 2018

Я сталкиваюсь с проблемой производительности в следующем коде, потому что количество тем, которые я должен сопоставить с текстом в сообщениях 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();
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...