Created
September 25, 2014 03:12
-
-
Save ryancole/f6366e809a6fa1f6ff46 to your computer and use it in GitHub Desktop.
array-based stack and queue, without using built in push pop
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 () { | |
var content = []; | |
return { | |
push: function (v) { | |
content[content.length] = v; | |
}, | |
pop: function () { | |
var result = content.splice(-1, 1); | |
if (result.length === 1) { | |
return result[0]; | |
} | |
} | |
}; | |
}; | |
function queue () { | |
var content = []; | |
return { | |
enqueue: function (v) { | |
content[content.length] = v; | |
}, | |
dequeue: function () { | |
var result = content.splice(0, 1); | |
if (result.length === 1) { | |
return result[0]; | |
} | |
} | |
}; | |
}; | |
var s = stack(); | |
console.log(s); | |
s.push(1); | |
s.push(2); | |
s.push(3); | |
console.log(s.pop()); | |
console.log(s.pop()); | |
console.log(s.pop()); | |
var q = queue(); | |
console.log(q); | |
q.enqueue(1); | |
q.enqueue(2); | |
q.enqueue(3); | |
console.log(q.dequeue()); | |
console.log(q.dequeue()); | |
console.log(q.dequeue()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment