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?
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:
split(" ")
based on a space which gives an array.forEach
method to iterate through all the elements in the spitted array.:?
to check if value already exists, if it does increment by one or assign it to 1.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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.