Created
April 21, 2018 16:51
-
-
Save Spuffynism/f559e5e70f557d23b70b260a9c3036c3 to your computer and use it in GitHub Desktop.
Simple vector implementation in js to help with amortized analysis
This file contains hidden or 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
| function Vector() { | |
| this.capacity = 1; | |
| this.elements = new Array(this.capacity); | |
| this.size = 0; | |
| this.add = (element) => { | |
| if (this.size > this.capacity) | |
| console.err('this.size > this.capacity'); | |
| if (this.size === this.capacity) { | |
| this.capacity *= 2; | |
| let t = new Array(this.capacity); | |
| for(let i = 0; i < this.size; i++) { | |
| t[i] = this.elements[i]; | |
| } | |
| this.elements = t; | |
| } | |
| this.elements[this.size++] = element; | |
| }; | |
| this.get = (i) => { | |
| return this.elements[i]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment