Created
July 12, 2018 03:00
-
-
Save bhongy/0006d452e75b4d1c9f1887e5e12508b8 to your computer and use it in GitHub Desktop.
Anti-if Stack Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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