1
\$\begingroup\$

Here is the original problem, and below is my solution (passing). It's asking to implement a queue with 2 stacks, which means I cannot simply use Array.shift. I wonder if the solution can be improved. Is there a better way than this to implement a queue with 2 stacks?

function processData(input) {
 var inputs = input.split('\n')
 var cmd;
 var inQueue = [],
 outQueue = []
 var len;
 function inQueueToOutQueue() {
 if (outQueue.length === 0) {
 len = inQueue.length;
 while (len-- > 0) {
 outQueue.push(inQueue.pop())
 }
 }
 }
 for (var i = 1, max = inputs[0]; i <= max; i++) {
 cmd = inputs[i].split(' ');
 switch (cmd[0]) {
 case '1':
 inQueue.push(cmd[1]);
 break;
 case '2':
 inQueueToOutQueue();
 outQueue.pop()
 break;
 case '3':
 inQueueToOutQueue();
 console.log(outQueue[outQueue.length - 1])
 break;
 default:
 }
 }
}
janos
113k15 gold badges154 silver badges396 bronze badges
asked Jun 22, 2017 at 16:26
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

You've pretty much nailed it. You don't really need the len variable here though, you could use a condition on inQueue.length directly.

len = inQueue.length;
while (len-- > 0) {
 outQueue.push(inQueue.pop())
}

The other thing I notice is the inconsistent use of semicolons. Sometimes you add at the end of statements, sometimes not. You could choose whichever way, but do it consistently.

Lastly, the empty default statement of the switch is unnecessary, you can drop it.

answered Jun 22, 2017 at 21:07
\$\endgroup\$
2
  • \$\begingroup\$ Thanks! you mean while (inQueue.length!==0)? \$\endgroup\$ Commented Jun 26, 2017 at 11:48
  • 1
    \$\begingroup\$ @kdenz yes, that's what I meant! \$\endgroup\$ Commented Jun 26, 2017 at 12:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.