作业要求
它可以帮我处理一段字符串信息,这段字符串信息是由英文单词组成,每两个单词之间有空格,
处理结果也为一段字符串,这个字符串应该每行只显示一个单词和它的数量,并且按出现频率倒序排列
- 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
思路
代码
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;
TDD.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截图
-
空字符串
-
一个单词
-
两个单词
-
三个单词
-
排序
-
最终
log日志
远成仓库
总结
- 终于知道git怎么用的了,之前还一脸蒙蔽,然后通过问同学、上网查询......反正就是各种不容易,感谢那些对我的问题很耐心的回答我的同学
-
还有就是远程仓库,最开始弄了好久它都说我那个git push命令有问题
后面问同学、网上查询才知道什么情况,原来是因为我没有创建SSH keys
- 谢谢teamleader和王凶一直耐心的回答我的问题,感动cry......