Factor out common infix op logic
This commit is contained in:
parent
1078dc3653
commit
5a34b0f6f7
1 changed files with 14 additions and 32 deletions
|
@ -58,44 +58,26 @@ function map(
|
|||
}
|
||||
}
|
||||
|
||||
function makeInfixOp(token:RegExp, leftBindingPower: number,rightBindingPower: number, op: (left: number, right: number) => Value | ErrorResult):TokenHandler {
|
||||
return {
|
||||
leftBindingPower,
|
||||
token,
|
||||
parse: ({ value: left }, matched, parser) =>
|
||||
map(parser.parseSubExpression(rightBindingPower), (right) => op(left, right)),
|
||||
}
|
||||
}
|
||||
|
||||
const Operators: TokenHandler[] = [
|
||||
{
|
||||
leftBindingPower: -1,
|
||||
token: NUMBER_TOKEN,
|
||||
parse: (left, matched) => ({ value: Number(matched) }),
|
||||
},
|
||||
{
|
||||
leftBindingPower: 10,
|
||||
token: PLUS_TOKEN,
|
||||
parse: ({ value: left }, matched, parser) =>
|
||||
map(parser.parseSubExpression(11), (right) => ({ value: left + right })),
|
||||
},
|
||||
{
|
||||
leftBindingPower: 10,
|
||||
token: MINUS_TOKEN,
|
||||
parse: ({ value: left }, matched, parser) =>
|
||||
map(parser.parseSubExpression(11), (right) => ({ value: left - right })),
|
||||
},
|
||||
{
|
||||
leftBindingPower: 20,
|
||||
token: TIMES_TOKEN,
|
||||
parse: ({ value: left }, matched, parser) =>
|
||||
map(parser.parseSubExpression(21), (right) => ({ value: left * right })),
|
||||
},
|
||||
{
|
||||
leftBindingPower: 20,
|
||||
token: FLOOR_TOKEN,
|
||||
parse: ({ value: left }, matched, parser) =>
|
||||
map(parser.parseSubExpression(21), (right) => ({
|
||||
value: Math.floor(left / right),
|
||||
})),
|
||||
},
|
||||
{
|
||||
leftBindingPower: 20,
|
||||
token: DIV_TOKEN,
|
||||
parse: ({ value: left }, matched, parser) =>
|
||||
map(parser.parseSubExpression(21), (right) => ({ value: left / right })),
|
||||
},
|
||||
makeInfixOp(PLUS_TOKEN, 10, 11, (left, right) => ({ value: left + right })),
|
||||
makeInfixOp(MINUS_TOKEN, 10, 11, (left, right) => ({ value: left - right })),
|
||||
makeInfixOp(TIMES_TOKEN, 10, 11, (left, right) => ({ value: left * right })),
|
||||
makeInfixOp(FLOOR_TOKEN, 10, 11, (left, right) => ({ value: Math.floor(left / right) })),
|
||||
makeInfixOp(DIV_TOKEN, 10, 11, (left, right) => ({ value: left / right })),
|
||||
];
|
||||
|
||||
const ZERO = { value: 0 };
|
||||
|
|
Loading…
Reference in a new issue