Last active
March 30, 2017 05:11
-
-
Save C-Rodg/8746cca67583708f7070a3e6569a0f09 to your computer and use it in GitHub Desktop.
A simple example using linear data structures of Stacks and Queues in Javascript.
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 Stack() { | |
this._size = 0; | |
this._storage = {}; | |
} | |
Stack.prototype.push = function(data) { | |
this._size += 1; | |
this._storage[this._size] = data; | |
}; | |
Stack.prototype.pop = function() { | |
let size = this._size; | |
if (size) { | |
const deletedData = this._storage[size]; | |
delete this._storage[size]; | |
this._size -= 1; | |
return deletedData; | |
} | |
}; | |
function Queue() { | |
this._storage = {}; | |
this._oldestIndex = 1; | |
this._newestIndex = 1; | |
} | |
Queue.prototype.size = function() { | |
return this._newestIndex - this._oldestIndex; | |
}; | |
Queue.prototype.enqueue = function(data) { | |
this._storage[this._newestIndex] = data; | |
this._newestIndex += 1; | |
}; | |
Queue.prototype.dequeue = function() { | |
let oldestIndex = this._oldestIndex; | |
let newestIndex = this._newestIndex; | |
if ( oldestIndex !== newestIndex ) { | |
const deletedData = this._storage[oldestIndex]; | |
delete this._storage[oldestIndex]; | |
this._oldestIndex += 1; | |
return deletedData; | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment