частота слов с использованием обратно совместимого синтаксиса

#javascript #html

#javascript #HTML

Вопрос:

У меня есть проблема, которую мне нужно решить двумя способами:

  1. Использование новейшего синтаксиса Javascript через Babel или аналогичного приблизительному ES6 / 7
  2. Использование обратно совместимого синтаксиса, который может работать во многих браузерах

Мне удалось решить это с помощью javascript (единственный известный мне способ)

 function wordFrequency(string) {
    var words = string.replace(/[.]/g, '').split(/[ ,!.";:-] /);
    var frequencyMap = {};
    words.forEach(function(w) {
        if (!frequencyMap[w]) {
            frequencyMap[w] = 0;
        }
        frequencyMap[w]  = 1;
    });
    
    return frequencyMap;
}

var input = wordFrequency("He smiled understandingly - much more than understandingly. It was one of those rare smiles with a quality of eternal reassurance in it, that you may come across four or five times in life. It faced - or seemed to face - the whole eternal world for an instant, and then concentrated on you with an irresistible prejudice in your favour. It understood you just as far as you wanted to be understood, believed in you as you would like to believe in yourself, and assured you that it had precisely the impression of you that, at your best, you hoped to convey. Precisely at that point it vanished - and I was looking at an elegant young rough-neck, a year or two over thirty, whose elaborate formality of speech just missed being absurd. Some time before he introduced himself I’d got a strong impression that he was picking his words with care. ");
Object.keys(input).sort().forEach(function(word) {
    console.log("count of: "   word   " = "   input[word]);
}); 

КАК мне написать этот код с обратно совместимым синтаксисом?

Комментарии:

1. Я добавил }); теперь синтаксической ошибки нет!

2. приятно, что это объект, у которого есть частота слов (у идентификатора тоже есть объект), поэтому разделение по пробелу естественно, чтобы были "" экземпляры для пробелов в строке .. удаление "" ключа из frequencyMap — это самое быстрое решение

3. Как бы я решил это, используя обратно совместимый синтаксис?

Ответ №1:

 function wordFrequency(string) {
    var words = string.replace(/[.]/g, '').split(/[ ,!.";:-] /);
    var frequencyMap = {};
    words.forEach(function(w) {
        if (!frequencyMap[w]) {
            frequencyMap[w] = 0;
        }
        frequencyMap[w]  = 1;
    });
    if(frequencyMap[""]){delete(frequencyMap[""])} //this would take out if there were extra spaces in the middle of the string like "asdf    a"
    return frequencyMap;
}

var input = wordFrequency("He smiled understandingly - much more than understandingly. It was one of those rare smiles with a quality of eternal reassurance in it, that you may come across four or five times in life. It faced - or seemed to face - the whole eternal world for an instant, and then concentrated on you with an irresistible prejudice in your favour. It understood you just as far as you wanted to be understood, believed in you as you would like to believe in yourself, and assured you that it had precisely the impression of you that, at your best, you hoped to convey. Precisely at that point it vanished - and I was looking at an elegant young rough-neck, a year or two over thirty, whose elaborate formality of speech just missed being absurd. Some time before he introduced himself I’d got a strong impression that he was picking his words with care. ");
Object.keys(input).sort().forEach(function(word) {
    console.log("count of: "   word   " = "   input[word]);
}); 

Комментарии:

1. это помогло устранить проблему с дополнительным пространством!