Jamgreen Jamgreen - 9 months ago 49
Javascript Question

Define variable inside while loop

How is

while (
stack.peek() in ops &&
p(stack.peek()) >= 10
) {
str += stack.pop();
}


rewritten so I call
.peek()
every time the loop runs, but only define it once?

I have thought about

const peek = stack.peek();
while (
peek in ops &&
p(peek) >= 10
) {
str += stack.pop();
}


but since I modify
stack
with
stack.pop()
inside the while loop, I guess the value of
stack.peek()
is changing every time, so I guess I have to redefine the variable inside the loop, but

let peek = stack.peek();
while (
peek in ops &&
p(peek) >= 10
) {
str += stack.pop();
peek = stack.peek();
}


also seems a bit wrong, so should it be something like

while (
let peek = stack.peek() &&
peek in ops &&
p(peek) >= 10
) {
str += stack.pop();
}


or

for (
let peek = stack.peek();
peek in ops && p(peek) >= 10;
peek = stack.peek()
) {
str += stack.pop();
}

Answer

Consider using while (true) with a break:

while (true) {
  const peek = stack.peek();
  if (!(peek in ops) || p(peek) < 10) break;
  str += stack.pop();
}

In theory you could also do:

while (
  (peek => peek in ops && p(peek) >= 10)(stack.peek())
) {
  str += stack.pop();
}

but that's pretty ugly. It's roughly equivalent to write

function pop(stack) {
  const peek = stack.peek();
  return peek in ops && p(peek) >= 10;
}

while(pop(stack)) str += stack.pop();

A for loop is not a bad idea either, and could be written as:

for (let peek; peek = stack.peek(), peek in ops && p(peek) >= 10; ) {
  str += stack.pop();
}

which again avoids duplicating the call to stack.peek().