Skip to content

Commit

Permalink
StackSet class
Browse files Browse the repository at this point in the history
  • Loading branch information
grxy committed Nov 30, 2016
1 parent b6f9ee6 commit 84b2e70
Show file tree
Hide file tree
Showing 3 changed files with 114 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/StackSet/StackSet.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import Stack from 'Stack';

class StackSet {
constructor(stackSize) {
if (typeof stackSize !== 'number' || stackSize < 1) {
throw new Error('stackSize must be at least 1.');
}

this.stackSize = stackSize;
}

stacks = [new Stack()]

isEmpty = () => !this.size()

pop = () => {
const last = this.stacks[this.stacks.length - 1];
const item = last.pop();

if (this.stacks.length > 1 && last.size() === 0) {
this.stacks.pop();
}

return item;
}

push = (item) => {
if (this.stacks[this.stacks.length - 1].size() === this.stackSize) {
this.stacks.push(new Stack());
}

this.stacks[this.stacks.length - 1].push(item);
}

size = () => {
let count = this.stacks[this.stacks.length - 1].size();

if (this.stacks.length > 1) {
count += (this.stacks.length - 1) * this.stackSize;
}

return count;
}
}

export default StackSet;
67 changes: 67 additions & 0 deletions src/StackSet/StackSet.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import StackSet from './StackSet';

let stack;

describe('StackSet', () => {
describe('with stackSize === 1', () => {
beforeEach(() => {
stack = new StackSet(1);
stack.push(1);
stack.push(2);
stack.push(3);
});

it('has the correct number of items', () => {
expect(stack.size()).toBe(3);
});

it('has the correct stack count', () => {
expect(stack.stacks.length).toBe(3);
});

describe('pop()', () => {
it('returns the correct item', () => {
expect(stack.pop()).toBe(3);
expect(stack.pop()).toBe(2);
expect(stack.pop()).toBe(1);
});

it('decreases the stack size', () => {
stack.pop();
expect(stack.size()).toBe(2);
});

it('descreases the stack count', () => {
stack.pop();
expect(stack.stacks.length).toBe(2);
});
});
});

describe('isEmpty()', () => {
it('returns true bu default', () => {
stack = new StackSet(5);
expect(stack.isEmpty()).toBe(true);
});

it('returns false when there are items', () => {
stack.push(4);
expect(stack.isEmpty()).toBe(false);
});
});

const throwCases = [0, -999, '', {}, [], undefined, null];

for (let i = 0; i < throwCases.length; i++) {
const input = throwCases[i];

it(`throws when initialized with ${JSON.stringify(input)}`, () => {
const throws = () => {
new StackSet(input);
};

expect(throws).toThrow();
});
}

});
1 change: 1 addition & 0 deletions src/StackSet/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default from './StackSet';

0 comments on commit 84b2e70

Please sign in to comment.