TTD-基础编程练习-FrequencyNumber

练习题目需求:

我想要一个nodejs小程序,
它可以帮我处理一段字符串信息,这段字符串信息是由英文单词组成,每两个单词之间有空格,
处理结果也为一段字符串,这个字符串应该每行只显示一个单词和它的数量,并且按出现频率倒序排列

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 流程图

TTD-基础编程练习-FrequencyNumber_第1张图片
流程图

代码:

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 截图

TTD-基础编程练习-FrequencyNumber_第2张图片
1.png

jasmint截图

TTD-基础编程练习-FrequencyNumber_第3张图片
2.png

个人总结

有难度,第一是安装git和nodejs,熟悉git和npm的各种操作指令,再有就是JS的语法,完成题目功能的逻辑反倒是比较好想,先传入字符串,开始按照空格分割,然后计数,排序再输出,意外经朋友提醒看到了教练在B站直播的视频,其中就有关于这个题目的讲解,认真看了,再写代码感觉轻松多了,关于TDD模式的编程也理解得更深深刻,还需要继续努力。

你可能感兴趣的:(TTD-基础编程练习-FrequencyNumber)