一: 本次練習涵蓋知識的說明講解
1.軟件支持烁竭,環(huán)境搭配
(1)Git環(huán)境配置
(2)Npm環(huán)境配置
(3)Jasmine環(huán)境配置
(4)Webstorm配置
關于環(huán)境配置:我開始是想用linux系統(tǒng)來寫這個任務的菲茬,于是我花了一大段的時間來在linux下裝環(huán)境,由于對linux系統(tǒng)的不熟悉颖变,在裝這幾個軟件的時候生均,花費了很多的時間,每次失敗了都去百度上找貼子腥刹,等等马胧,但是以失敗告終。最后暫時放棄linux衔峰,又重新再windows下完成任務佩脊。
2.知識需求
(1)JS的基本語法和函數(shù)
二:思考過程(TDD模式)
1.從測試入手蛙粘,先保證滿足測試先過。
2.再將代碼從特殊的(滿足一個測試的時候)威彰,變成具體化(滿足任意的條件)出牧。
3.重復寫出不同的測試,使每種情況都滿足歇盼。
4.將最后得到的代碼重新整理舔痕,提高可讀性。
三:測試和實現(xiàn)的代碼
測試
"use strict";
var _ = require("lodash");
var chai = require("chai");
var sinon = require("sinon");
var sinonChai = require("sinon-chai");
var expect = chai.expect;
chai.use(sinonChai);
var main = require("../testmain/main.js");
describe("測試描述",function () {
sinon.spy(console, 'log');
it("傳入'he' 返回‘he 1’", function () {
var result = main('he');
var expect_string = 'he 1';
expect(expect_string).to.equal(result);
});
it("傳入'he is' 返回‘he 1\nis 1’", function () {
var result = main('he is');
var expect_string = 'he 1\nis 1';
expect(expect_string).to.equal(result);
});
it("傳入'he is ' 返回‘he 1\nis 1’", function () {
var result = main(' he is ');
var expect_string = 'he 1\nis 1';
expect(expect_string).to.equal(result);
});
it("傳入'he he is ' 返回‘he 2\nis 1’", function () {
var result = main(' he he is ');
var expect_string = 'he 2\nis 1';
expect(expect_string).to.equal(result);
});
it("傳入'he is a he he is is is' 返回‘is 4\nhe 3\na 1’", function () {
var result = main('he is a he he is is is');
var expect_string = 'is 4\nhe 3\na 1';
expect(expect_string).to.equal(result);
});
});
實現(xiàn):
function main(string) {
var words = string.trim().split(/\s+/);
var splitWords = [];
var num = [];
function findPositon(arr, w) {
var ret = -1;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === w) {
ret = i;
}
}
return ret;
}
function classify(words,num) {
for (var i = 0; i < words.length; i++) {
var pos = findPositon(splitWords, words[i]);
if (pos !== -1) {
num[pos]++;
} else {
splitWords.push(words[i]);
num.push(1);
}
}
}
function format(splitWords,num) {
var answer = '';
for (var i = 0; i < splitWords.length; i++) {
answer += splitWords[i] + ' ' + num[i];
if (i !== splitWords.length - 1) {
answer += '\n';
}
}
return answer;
}
function SortWords(splitWords,num) {
for (var i = 0; i < num.length; i++) {
for (var j = i; j < num.length; j++) {
if (num[i] < num[j]) {
var temp = num[i];
num[i] = num[j];
num[j] = temp;
temp = splitWords[i];
splitWords[i] = splitWords[j];
splitWords[j] = temp;
}
}
}
}
classify(words,num);
SortWords(splitWords,num);
return format(splitWords,num);
}
module.exports = main;