let { Language, Skip, EventType } = require("turingjs");
// Step 1: Define a new language
let brainfuck = new Language()
.token({
'+': state => { state.stack[state.index]++ },
'-': state => { state.stack[state.index]-- },
'>': state => { state.index++ },
'<': state => { state.index-- },
',': state => { state.stack[state.index] = state.data.in.shift().charCodeAt(0) },
'.': state => { state.data.out.push(String.fromCharCode(state.stack[state.index])) },
']': (state, token) => { state.tokenPointer = state.data.loops.pop() - 1 },
'[': (state, token) => {
if (state.stack[state.index] === 0) {
return Skip.until.balanced('[', ']', 1);
}
state.data.loops.push(token.position)
}
})
.on('eof', state => state.data.loops.length === 0)
.data({ in: [], out: [], loops: [] });
// Step 2: Run some code in the new language
brainfuck
.data({ in: 'ABC'.split('') })
.run('+++[->,.+++.<]') // Takes 3 letters. Prints each letter + that letter incremented by 3
.then(finalState => console.log(finalState.data.out.join(''))/* ADBECF */)
.catch(error => console.log(error));