Skip to content

Instantly share code, notes, and snippets.

@ooflorent
Created January 25, 2014 00:44
Show Gist options
  • Save ooflorent/8609899 to your computer and use it in GitHub Desktop.
Save ooflorent/8609899 to your computer and use it in GitHub Desktop.
var Token = {
Concatenate: '0',
Increment: '1',
Decrement: '2',
Multiply: '3',
Divide: '4',
Add: '5',
Subtract: '6',
Exponent: '7',
Modulus: '8',
RotateRight: '9',
RotateLeft: 'A',
Duplicate: 'B',
DoubleDuplicate: 'C',
Swap: 'D',
DoubleSwap: 'E',
Delete: 'F'
};
function parse(input, mem) {
var a, b, c, d;
var stack = mem ? mem.slice() : [0];
for (var i = 0, n = input.length; i < n; i++) {
switch (input[i]) {
case Token.Concatenate:
a = stack.pop();
b = stack.pop();
stack.push(parseInt([b] + a));
break;
case Token.Increment:
a = stack.pop();
stack.push(a + 1);
break;
case Token.Decrement:
a = stack.pop();
stack.push(a - 1);
break;
case Token.Multiply:
a = stack.pop();
b = stack.pop();
stack.push(b * a);
break;
case Token.Divide:
a = stack.pop();
b = stack.pop();
stack.push(b / a | 0);
break;
case Token.Add:
a = stack.pop();
b = stack.pop();
stack.push(b + a);
break;
case Token.Subtract:
a = stack.pop();
b = stack.pop();
stack.push(b - a);
break;
case Token.Exponent:
a = stack.pop();
b = stack.pop();
stack.push(Math.pow(b, a));
break;
case Token.Modulus:
a = stack.pop();
b = stack.pop();
stack.push(b % a);
break;
case Token.RotateRight:
a = stack.shift();
stack.push(a);
break;
case Token.RotateLeft:
a = stack.pop();
stack.unshift(a);
break;
case Token.Duplicate:
a = stack[stack.length - 1];
stack.push(a);
break;
case Token.DoubleDuplicate:
a = stack[stack.length - 1];
b = stack[stack.length - 2];
stack.push(b, a);
break;
case Token.Swap:
a = stack.pop();
b = stack.pop();
stack.push(a, b);
break;
case Token.DoubleSwap:
a = stack.pop();
b = stack.pop();
c = stack.pop();
d = stack.pop();
stack.push(b, a, d, c);
break;
case Token.Delete:
stack.pop();
break;
default:
throw new SynxtaxError('Invalid token "' + input[i] + '"');
}
}
return stack.reverse();
}
exports.Token = Token;
exports.parse = parse;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment