練習(xí)題目需求:
我想要一個nodejs小程序,
它可以幫我處理一段字符串信息,這段字符串信息是由英文單詞組成,每兩個單詞之間有空格,
處理結(jié)果也為一段字符串,這個字符串應(yīng)該每行只顯示一個單詞和它的數(shù)量,并且按出現(xiàn)頻率倒序排列
Example
input:
“it was the age of wisdom it was the age of foolishness it is”
output
it 3
was 2
the 2
age 2
of 2
wisdom 1
foolishness 1
is 1
Tasking 流程圖

代碼:
main.js
var format = function (word,count){
return word +" "+ count;
};
var group = function(wordArray){
return wordArray.reduce((array,word) => {
let entry = array.find((e) =>e.word ===word);
if(entry){
entry.count++;
}else{
array.push({word:word,count:1});
}
return array;
},[]);
};
var split = function(words){
return words.split(/\s+/);
};
var sort = function(groupedWords){
groupedWords.sort((s,y)=>y.count - x.count);
};
function main(words){
if(words!== ''){
let wordArray = words.split(/\s+/);
let groupedWords = group(wordArray);
groupedWords.sort((x,y) =>y.count -x.count);
return groupedWords.map((e) => format(e.word,e.count)).join('\r\n');
}
return '';
}
module.exports = main;
Frequency NumberSpec.js
var main = require("./main.js");
describe("Word Frequency",function(){
it("returns empty string given empty string",function(){
var result = main('');
expect(result).toEqual('');
});
it("returns string given one word",function(){
var result = main('he');
expect(result).toEqual('he 1');
});
it("returns string given two different words",function(){
var result = main('he is');
expect(result).toEqual('he 1\r\nis 1');
});
it("returns string given duplicated words",function(){
var result = main('he is he');
expect(result).toEqual('he 2\r\nis 1');
});
it("returns string given duplicated words need to be sorted",function(){
var result = main('he is is');
expect(result).toEqual('is 2\r\nhe 1');
});
it("returns string given words splited by multiple spaces",function(){
var result = main('he is');
expect(result).toEqual('he 1\r\nis 1');
});
it("returns string given words splited by multiple spaces",function(){
var result = main('it was the age of wisdom it was the age of foolishness it is');
expect(result).toEqual('it 3\r\nwas 2\r\nthe 2\r\nage 2\r\nof 2\r\nwisdom 1\r\nfoolishness 1\r\nis 1');
});
});
GIT 截圖

jasmint截圖

個人總結(jié)
有難度,第一是安裝git和nodejs,熟悉git和npm的各種操作指令,再有就是JS的語法,完成題目功能的邏輯反倒是比較好想,先傳入字符串,開始按照空格分割,然后計數(shù),排序再輸出,意外經(jīng)朋友提醒看到了教練在B站直播的視頻,其中就有關(guān)于這個題目的講解,認(rèn)真看了,再寫代碼感覺輕松多了,關(guān)于TDD模式的編程也理解得更深深刻,還需要繼續(xù)努力。