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:
        }
    }

}
\$\endgroup\$
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.

\$\endgroup\$
  • \$\begingroup\$ Thanks! you mean while (inQueue.length!==0)? \$\endgroup\$ – kdenz Jun 26 '17 at 11:48
  • 1
    \$\begingroup\$ @kdenz yes, that's what I meant! \$\endgroup\$ – janos Jun 26 '17 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.