Simulated stack que
simulation of a stack using js and arrays and linked lists
by steven dixon
HTML
<link rel="stylesheet" href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css">
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.3.0/chai.min.js"></script>
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
</head>
<body>
<div id="mocha"></div>
</body>
</html>
JavaScript
mocha.setup('bdd');
var expect = chai.expect;
function Stack() {
this.top = null;
this.length = 0;
}
Stack.prototype.push = function(node) {
if (!this.top) {
this.top = node
} else {
this.previous = this.top;
this.top = node;
this.top.next = this.previous;
}
this.length += 1;
return this.length;
}
Stack.prototype.pop = function() {
if (!this.top) {
return 'empty';
} else {
if (this.top.next) {
this.top = this.top.next;
this.length -= 1;
return this.top;
} else {
return 'empty';
}
}
}
Stack.prototype.print = function() {
if (this.top) {
return printList(this.top)
}
}
function Queue() {
this.top = null;
this.length = 0;
}
Queue.prototype.push = function(node) {
if (!this.top) {
this.top = node;
} else {
let n = this.top;
while (n.next) {
n = n.next;
}
n.next = node;
}
this.length += 1;
return this.length;
}
Queue.prototype.pop = Stack.prototype.pop;
Queue.prototype.print = function() {
if (this.top) {
return printList(this.top)
}
}
function node(data, func) {
this.func = func;
this.data = data;
this.next = null;
}
function add(data) {
if (Array.isArray(data)) {
return data.reduce((acc, cur) => {
return acc + cur
}, 0);
}
return data;
}
function printList(node) {
if (!node.next) {
return node.func(node.data);
} else {
return node.func(node.data) + " " + printList(node.next);
}
}
describe('New Stack', function() {
let test = new Stack();
it('Should be a new object', function() {
chai.expect(test).to.be.an('object');
});
it('Should have 2 keys', function() {
chai.expect(test).to.have.all.key('top', 'length');
});
it('Should be able push a new node into the stack', function() {
chai.expect(test.push({
func: add,
data: [1, 2]
})).to.equal(1);
chai.expect(test.push({
func: add,
data: [4, 2]
})).to.equal(2);
});
it('Should be...