Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created January 31, 2017 20:54
Show Gist options
  • Select an option

  • Save jasonwaters/71b44a7a2f0fd7b117b07978559d6620 to your computer and use it in GitHub Desktop.

Select an option

Save jasonwaters/71b44a7a2f0fd7b117b07978559d6620 to your computer and use it in GitHub Desktop.
queue
// solution for this hackerrank challenge
// https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks
function Queue() {
this.data = [];
this.operations = {
1: args => this.enqueue(...args),
2: args => this.dequeue(...args),
3: args => this.print(...args)
};
}
// add a new element to the end of the queue.
Queue.prototype.enqueue = function(value) {
this.data.push(value);
};
// remove the element from the front of the queue and return it.
Queue.prototype.dequeue = function() {
return this.data.shift();
};
// print the element at the front of the queue.
Queue.prototype.print = function() {
if(this.data.length > 0) {
console.log(this.data[0]);
}
};
Queue.prototype.do = function(operation, ...args) {
this.operations[operation](args);
};
function processData(input) {
let q = new Queue();
let operations = input.split('\n').slice(1).map(value => value.trim().split(' ').map(value => parseInt(value)));
operations.forEach(operation => q.do(...operation));
}
processData(`10
1 42
2
1 14
3
1 28
3
1 60
1 78
2
2`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment