TDD编程:Word Frequency

本次练习要求如下:1.git学习2.Nodejs学习3.用Nodejs和Git完成TDD编程

知识思路github地址

知识

手把手教你如何安装和使用Karma-Jasmine
推荐!手把手教你使用Git
github地址

Git是世界上最先进的分布式版本控制系统,通过创建版本库,实现对文件的控制。
Node.js则相当于提供了一个快速执行js语句的平台。
TDD模式:单元测试驱动开发。每次只需要针对特定的需求编写代码,在测试代码的基础之上,大大节约了时间成本。代码重构,软件架构,使软件需要继续开发时,成本大大降低。
思路

快捷键
TDD - Word Frequency

TDD编程:Word Frequency_第1张图片
Paste_Image.png

实现代码

/**
 * Created by Administrator on 2017/4/19.
 */
var formatWordAndCount = 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((x, y) = > y.count - x.count);
};
var format = function (groupedWords) {
    return groupedWords.map((e) = > formatWordAndCount(e.word, e.count).join('\r\n');
};
function (words) {
    if (words !== ''){
        let wordArray = split(words);
        let groupedWords = group(wordArray);
        sort(groupedWords);
        return format(groupedWords);
    }
    return ''
}

module.exports = main;

测试代码

/**
 * Created by Administrator on 2017/4/19.
 */
"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("../lib/main.js");

describe("Word Frequency", function(){
    it("returns empty string given empty string", function(){
        var result = main('');
        expect(return).to.equal('');
    });

    it("returns empty given one word", function(){
        var result = main('he');
        expect(return).to.equal('he 1');
    });

    it("returns empty given two different words", function(){
        var result = main('he is');
        expect(return).to.equal('he 1\r\nis 1');
    });

    it("returns empty given duplicated words", function(){
        var result = main('he is he');
        expect(return).to.equal('he 2\r\nis 1');
    });

    it("returns empty given duplicated words need  to be sorted", function(){
        var result = main('he is is');
        expect(return).to.equal('is 2\r\nhe 1');
    });

    it("returns empty given words splited by mutiple spaces", function(){
        var result = main('he    is');
        expect(return).to.equal('he 1\r\nis 1');
    });
});

git log 截图

TDD编程:Word Frequency_第2张图片
Paste_Image.png

你可能感兴趣的:(TDD编程:Word Frequency)