问题
For example for the input "olly olly in come free"
The program should return:
olly: 2
in: 1
come: 1
free: 1
The tests are written as:
var words = require('./word-count');
describe("words()", function() {
it("counts one word", function() {
var expectedCounts = { word: 1 };
expect(words("word")).toEqual(expectedCounts);
});
//more tests here
});
How do I start in my word-count.js file? Create a method words() or a module Words() and make an expectedCount method in there and export it?
Do I treat the string as an array or an object? In the case of objects, how do I start breaking them into words and iterate for the count?
回答1:
function count(str) {
var obj = {};
str.split(" ").forEach(function(el, i, arr) {
obj[el] = obj[el] ? ++obj[el] : 1;
});
return obj;
}
console.log(count("olly olly in come free"));
This code should get just what you want.
For more understanding on the code I would advice you to go through array prototype functions and string prototype functions.
For simple understanding of what I`m doing here:
- Create a count function which returns an object of count of all occurrences of words.
- Split the string using
split(" ")
based on a space which gives an array. - Use
forEach
method to iterate through all the elements in the spitted array. - Ternary operator
:?
to check if value already exists, if it does increment by one or assign it to 1.
Array.prototype String.prototype
回答2:
Here's how you do it
word-count.js
function word-count(phrase){
var result = {}; // will contain each word in the phrase and the associated count
var words = phrase.split(' '); // assuming each word in the phrase is separated by a space
words.forEach(function(word){
// only continue if this word has not been seen before
if(!result.hasOwnProperty(word){
result[word] = phrase.match(/word/g).length;
}
});
return result;
}
exxports.word-count = word-count;
来源:https://stackoverflow.com/questions/26825786/count-the-occurrence-of-each-word-in-a-phrase-using-javascript