Last active
February 9, 2017 05:31
-
-
Save mr-rob0to/160208a440c5380f41ea1693ec1973a3 to your computer and use it in GitHub Desktop.
JS Array Re-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
// Exercise to re-implement a Javascript Array from scratch | |
// We are using a quazi implementation of memory (JS Array) to mimic directly accessing your system memory and simulating a block of memory | |
// const memory = require('./memory'); <=== fake memory using JS Array | |
// Initialize Array object (using ES6 class syntax here) | |
class Array { | |
constructor() { | |
this.length = 0; | |
this._capacity = 0; | |
this.ptr = memory.allocate(this.length); | |
} | |
const RATIO_SIZE = 3; | |
push(value) { | |
// first check if we have enough space to add new value based on current capacity. If not, resize and re-allocate space at RATIO_SIZE for room to grow in future | |
if (this.length >= this._capacity) { | |
this._resize((this.length + 1) * Array.RATIO_SIZE); | |
} | |
memory.set(this.ptr + this.length, value); | |
// update length property of Array (increment by one here) | |
this.length++; | |
} | |
_resize(size) { | |
// grab reference to current pointer | |
let oldPtr = this.ptr; | |
// update pointer based on the new memory allocation size | |
this.ptr = memory.allocate(size) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment