Skip to content

JS-based interpreter #4

@MarcelloTheArcane

Description

@MarcelloTheArcane
function bf (program) {
  const bracketDirectory = []
  const bracketStore = []

  for (let index = 0; index < program.length; ++ index) {
    if (program[i] === '[') {
	  bracketStore.push(i)
    } else if (program[i] === ']') {
      bracketDirectory[bracketDirectory[i] = bracketStore.pop()] = index
    }
  }

  outputArray = []
  const db = [0]
  let dbIndex = 0
  let programIndex = 0

  const programHandler = {
	'>': () => {
	  db[++dbIndex] = db[dbIndex] || 0
    },
    '<': () => {
	  --dbIndex
    },
    '+': () => {
	  ++db[dbIndex]
    },
    '-': () => {
	  --db[dbIndex]
    },
    '[': () => {
	  db[dbIndex] || (programIndex = bracketDirectory[programIndex])
    },
    ']': () => {
	  db[dbIndex] && (programIndex = bracketDirectory[programIndex])
    },
	',': () => {
	  db[dbIndex] = prompt('Insert value at position ' + programIndex).charCodeAt(0)
    },
    '.': () => {
	  outputArray.push(String.fromCharCode(db[dbIndex]))
    },
  }

  for (programIndex = 0; programIndex < program.length; ++programIndex) {
    if (programHandler[program[programIndex]] !== undefined) {
	  programHandler[program[programIndex]]()
    }
  }

  return outputArray.join('')
}

port to C++

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions