Reputation: 35
I have a problem I need to solve in 2 ways:
I have managed to solve it with javascript(the only way I know how)
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]);
});
HOW do I write this code with backwards compatible syntax?
Upvotes: 0
Views: 51
Reputation: 4337
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]);
});
Upvotes: 1