Created
July 27, 2018 01:22
-
-
Save drtconway/557f07ceb23b3aab374bf03974dad32f to your computer and use it in GitHub Desktop.
Double Ended Queue (Deque) in Javascript
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
function Deque() { | |
var rev = [] | |
var fwd = [] | |
this.size = function() { | |
return rev.length + fwd.length | |
} | |
this.push_front = function(itm) { | |
rev.push(itm) | |
} | |
this.push_back = function(itm) { | |
fwd.push(itm) | |
} | |
this.pop_front = function() { | |
//assert(this.size() > 0) | |
if (rev.length == 0) { | |
while (fwd.length > 0) { | |
var itm = fwd.pop() | |
rev.push(itm) | |
} | |
} | |
return rev.pop() | |
} | |
this.pop_back = function() { | |
//assert(this.size() > 0) | |
if (fwd.length == 0) { | |
while (rev.length > 0) { | |
var itm = rev.pop() | |
fwd.push(itm) | |
} | |
} | |
return fwd.pop() | |
} | |
this.toList = function() { | |
var lst = [] | |
for (var i = 0; i < rev.length; i++) { | |
var j = rev.length - 1 - i | |
lst.push(rev[j]) | |
} | |
for (var i = 0; i < fwd.length; i++) { | |
lst.push(fwd[i]) | |
} | |
return lst | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment