Skip to content

Instantly share code, notes, and snippets.

@bhongy
Created July 12, 2018 03:00
Show Gist options
  • Save bhongy/0006d452e75b4d1c9f1887e5e12508b8 to your computer and use it in GitHub Desktop.
Save bhongy/0006d452e75b4d1c9f1887e5e12508b8 to your computer and use it in GitHub Desktop.
Anti-if Stack Implementation
// idea from: https://www.youtube.com/watch?v=APUCMSPiNh4
class IllegalStateError extends Error {
constructor(...args) {
super(...args);
}
}
class Empty {
size() {
return 0;
}
top() {
throw new IllegalStateError('The stack is empty.');
}
pop() {
throw new IllegalStateError('The stack is empty.');
}
push(newTop) {
return new NonEmpty(newTop, this);
}
}
class NonEmpty {
constructor(newTop, previous) {
this.top = newTop;
this.tail = previous;
}
size() {
return 1 + this.tail.size();
}
top() {
return this.top;
}
pop() {
return this.tail;
}
push(newTop) {
return new NonEmpty(newTop, this);
}
}
const stack = new Empty().push('foo').push('bar');
console.log(stack.tail);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment