Start writing expressions with jsep

This commit is contained in:
Dana Sulit 2017-10-30 11:45:25 -04:00
parent 65f89c3371
commit 1050b712bb
8 changed files with 73 additions and 12 deletions

5
package-lock.json generated
View File

@ -3785,6 +3785,11 @@
}
}
},
"jsep": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/jsep/-/jsep-0.3.2.tgz",
"integrity": "sha512-b/QP7Apx3EEvFk5/O+bp8BmMP97EypcxqTXWs8nK+Mr9DKhxLX/EWlxERtCZ7mwWIssnOLGCGMoJ08oMiwrjIw=="
},
"jsesc": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz",

View File

@ -46,5 +46,8 @@
"jest": "^21.2.1",
"lint-staged": "^4.3.0",
"prettier": "^1.7.4"
},
"dependencies": {
"jsep": "^0.3.2"
}
}

11
src/ast-to-expression.js Normal file
View File

@ -0,0 +1,11 @@
function astToExpression(input) {
if (input.value) return input.value;
if (input.type === 'BinaryExpression') {
const left = astToExpression(input.left);
const right = astToExpression(input.right);
return [input.operator, left, right];
}
}
export default astToExpression;

View File

@ -1,5 +0,0 @@
function returnTrue() {
return true;
}
export default returnTrue;

7
src/string-to-ast.js Normal file
View File

@ -0,0 +1,7 @@
import jsep from 'jsep';
function stringToAst(input) {
return jsep(input);
}
export default stringToAst;

View File

@ -0,0 +1,24 @@
import stringToAst from '../src/string-to-ast';
import astToExpression from '../src/ast-to-expression';
describe('astToExpression', () => {
test('3', () => {
const actual = astToExpression(stringToAst('3'));
expect(actual).toBe(3);
});
test('3 + 4', () => {
const actual = astToExpression(stringToAst('3 + 4'));
expect(actual).toEqual(['+', 3, 4]);
});
test('(3 + 4) / 7', () => {
const actual = astToExpression(stringToAst('(3 + 4) / 7'));
expect(actual).toEqual(['/', ['+', 3, 4], 7]);
});
test('((3 + 4) * 2) / 7', () => {
const actual = astToExpression(stringToAst('((3 + 4) * 2) / 7'));
expect(actual).toEqual(['/', ['*', ['+', 3, 4], 2], 7]);
});
});

View File

@ -1,7 +0,0 @@
import returnTrue from '../src/index';
describe('returnTrue', function() {
test('returns true', function() {
expect(returnTrue()).toBe(true);
});
});

View File

@ -0,0 +1,23 @@
import stringToAst from '../src/string-to-ast';
describe('stringToAst', () => {
test('3 + 4', () => {
const actual = stringToAst('3 + 4');
const output = {
type: 'BinaryExpression',
operator: '+',
left: {
type: 'Literal',
value: 3,
raw: '3'
},
right: {
type: 'Literal',
value: 4,
raw: '4'
}
};
expect(actual).toEqual(output);
});
});