Skip to content

Instantly share code, notes, and snippets.

@yitznewton
Created July 8, 2015 18:58
Show Gist options
  • Save yitznewton/68f2ceaea9d27bb38c70 to your computer and use it in GitHub Desktop.
Save yitznewton/68f2ceaea9d27bb38c70 to your computer and use it in GitHub Desktop.
Linked List Kata
// $ brew install node
// $ npm init
// $ npm install -S mocha chai sinon
//
// $ npm test
var sinon = require("sinon");
var expect = require("chai").expect;
var LinkedList = function() {
var head, last;
this.append = function(value) {
var newNode = { value: value };
if (typeof head === "undefined") {
head = newNode;
} else {
last.next = newNode;
}
last = newNode;
};
this.each = function(callback) {
var current = head;
while (typeof current !== "undefined") {
callback(current.value);
current = current.next;
}
};
};
describe("LinkedList", function() {
var list;
beforeEach(function() {
list = new LinkedList();
});
describe("iterating", function() {
describe("before appending any elements", function() {
it("does not call the callback", function() {
var callback = sinon.spy();
list.each(callback);
expect(callback.callCount).to.eql(0);
});
});
describe("after appending one element", function() {
var element = "A";
beforeEach(function() {
list.append(element);
});
it("calls the callback once", function() {
var callback = sinon.spy();
list.each(callback);
expect(callback.callCount).to.eql(1);
});
it("calls the callback with the element", function() {
var callback = sinon.spy();
list.each(callback);
expect(callback.getCall(0).args).to.eql([element]);
});
});
describe("after appending two elements", function() {
var first = "A";
var second = "B";
beforeEach(function() {
list.append(first);
list.append(second);
});
it("calls the callback twice", function() {
var callback = sinon.spy();
list.each(callback);
expect(callback.callCount).to.eql(2);
});
it("calls the callback with the elements", function() {
var callback = sinon.spy();
list.each(callback);
expect(callback.getCall(0).args).to.eql([first]);
expect(callback.getCall(1).args).to.eql([second]);
});
});
describe("after appending three elements", function() {
var first = "A";
var second = "B";
var third = "C";
beforeEach(function() {
list.append(first);
list.append(second);
list.append(third);
});
it("calls the callback three times", function() {
var callback = sinon.spy();
list.each(callback);
expect(callback.callCount).to.eql(3);
});
it("calls the callback with the elements", function() {
var callback = sinon.spy();
list.each(callback);
expect(callback.getCall(0).args).to.eql([first]);
expect(callback.getCall(1).args).to.eql([second]);
expect(callback.getCall(2).args).to.eql([third]);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment