Replicating a Dynamic Array in JavaScript and PHP

Use Case:

Arrays are an extremely common data structure in computers and programming. If you've been programming for more than a week, you've used arrays to store lists or series of values regardless of type.

A drawback to arrays, however, are that they are of fixed size meaning that when they're called their capacity is established. Fortunately, we have data structures called dynamic arrays that allow us to automatically resize (or replace) the array with a new one when the capacity is about to be breached. Even more fortunately for us as programmers is that pretty much all programming languages we use today will take care of this for us behind the seens, meaning that we don't need to go through the process of creating a new array, updating the pointer (and capacity) and deleting the old array each time our array size is extended beyond its initial size.

Hey, Tyler here. I'm currently working on some great web development and digital marketing products and services over at ZeroToDigital.

If that sounds interesting to you, please check it out!

But, for learning purposes, below are examples of what this might look like if we needed to do so in both JavaScript - just to have a better understanding and appreciation of what is happening behind the scenes.

JavaScript

// Creates a stack
var Stack = function(capacity) {
	this.capacity = capacity
	this.size = 0
	this.storage = {}
}

// Adds a value onto the end of the stack
Stack.prototype.push = function(value) {

	// If capacity reached
	if (this.size == this.capacity) {
		this.capacity = this.capacity * 2

		// Simulating replacing old array with new array
		temp = this.storage
		delete this.storage
		this.storage = temp
		this.storage[this.size] = value
	} else {
		this.storage[this.size] = value
	}
	this.size++
}

var stack = new Stack(3)
stack.push(4)
stack.push(1)
stack.push(2)
console.log(stack.capacity) // 3
stack.push(5)
console.log(stack.capacity) // 6

We're starting with the constant-time JavaScript stack that we created previously, but updating the Stack for 'capacity' and 'size'. Then, upon pushing to the stack we're checking if the current size matches the capacity. If it does, then our stack is full and we need to create a new array (not done here but simulated) with a new capacity before adding the new value to it.

After calling the stack, we can log out the capacity values before breaching the capacity size and then after.

Tweet me @tylerewillis

Or send an email:

And support me on Patreon