if_for_loop
by Richard Hunter
JavaScript
const IF = "if"
const FI = "fi"
const FOR = "for"
const DONE = "done"
const stack = []
const lines = ["if", "if", "for", "done", "fi", "fi"]
lines.forEach((line) => {
if (line === IF) {
stack.push({
type: IF,
})
console.log("open if block")
} else if (line === FI) {
const currentBlock = stack[stack.length - 1]
if (currentBlock?.type === IF) {
stack.pop()
console.log("close if block")
} else {
throw new Error("syntax error")
}
} else if (line === FOR) {
stack.push({
type: FOR,
})
console.log("open for block")
} else if (line === DONE) {
const currentBlock = stack[stack.length - 1]
if (currentBlock?.type === FOR) {
stack.pop()
console.log("close for block")
} else {
throw new Error("syntax error")
}
}
})