Skip to content

Commit

Permalink
Add better list parser
Browse files Browse the repository at this point in the history
  • Loading branch information
pyldin601 committed Oct 27, 2017
1 parent 6f6fda1 commit 80d70a4
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,31 @@ const parse = (program: string[]): IToken[] => {

const splitChars = (chars: string) => chars.split('');

const toListInternal = (tokens: IToken[], depth = 0): any[] => {
const iterateList = optimizeTailCall(([head, ...tail]: IToken[], acc) => {
if (_.isNil(head)) {
if (depth > 0) {
throw new Error('0 non-closed parenthesis found');
}
return { acc, tail: [] };
}
if (head === OPEN_PARENTHESIS) {
const parseResult = toListInternal(tail, depth + 1);
return iterateList(parseResult.tail, [...acc, parseResult.acc]);
}
if (head === CLOSE_PARENTHESIS) {
if (depth === 0) {
throw new Error('0 superfluous open parenthesis found');
}
return { acc, tail };
}
return iterateList(tail, [...acc, head]);
});
return iterateList(tokens, []);
};

const toList = (tokens: IToken[]): any[] => {
return toListInternal(tokens, 0).acc;
};

export default compose(flattenize, parse, splitChars);

0 comments on commit 80d70a4

Please sign in to comment.