一: 本次练习涵盖知识的说明讲解
1.软件支持,环境搭配
(1)Git环境配置
(2)Npm环境配置
(3)Jasmine环境配置
(4)Webstorm配置
关于环境配置:我开始是想用linux系统来写这个任务的,于是我花了一大段的时间来在linux下装环境,由于对linux系统的不熟悉,在装这几个软件的时候,花费了很多的时间,每次失败了都去百度上找贴子,等等,但是以失败告终。最后暂时放弃linux,又重新再windows下完成任务。
2.知识需求
(1)JS的基本语法和函数
二:思考过程(TDD模式)
1.从测试入手,先保证满足测试先过。
2.再将代码从特殊的(满足一个测试的时候),变成具体化(满足任意的条件)。
3.重复写出不同的测试,使每种情况都满足。
4.将最后得到的代码重新整理,提高可读性。
三:测试和实现的代码
测试
"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);
});
});
实现:
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;