Created
August 19, 2017 03:41
-
-
Save ndugger/45f0f9039bd077de1112e538ca6c1707 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import vm from 'vm'; | |
| export default { | |
| [ '>' ] (input) { | |
| const context = { | |
| Array, | |
| Boolean, | |
| Buffer, | |
| Date, | |
| Map, | |
| Math, | |
| Number, | |
| Object, | |
| Promise, | |
| RegExp, | |
| Set, | |
| String, | |
| Symbol, | |
| WeakMap, | |
| WeakSet, | |
| setTimeout | |
| }; | |
| const result = vm.runInNewContext(input, context, { timeout: 10000 }); | |
| return `Eval: **\`${ JSON.stringify(result) }\`**`; | |
| }, | |
| math (input) { | |
| let expression = input.replace(/\s/g, ''); | |
| const numbers = /((?:\d|\.)+)/; | |
| const groups = /\((.+?)\)/; | |
| const methods = [ | |
| { op: /((?:\^|\*\*))/, fn (x, o, y) { return Math.pow(x, y) } }, | |
| { op: /(\*|\/|\%)/, fn (x, o, y) { | |
| switch (o) { | |
| case '*': return x * y; | |
| case '/': return x / y; | |
| case '%': return x % y; | |
| } | |
| } }, | |
| { op: /(\+)/, fn (x, o, y) { return x + y } }, | |
| { op: /(\-)/, fn (x, o, y) { return x - y } } | |
| ]; | |
| const evaluate = terms => { | |
| for (const { op, fn } of methods) { | |
| const regex = new RegExp(numbers.source + op.source + numbers.source); | |
| while (terms.match(regex)) { | |
| const [ term, x, o, y ] = terms.match(regex); | |
| terms = terms.replace(term, fn(Number(x), o, Number(y))); | |
| } | |
| } | |
| return terms; | |
| } | |
| while (expression.match(groups)) { | |
| const [ group, terms ] = expression.match(groups); | |
| expression = expression.replace(group, evaluate(terms)); | |
| } | |
| return `Math: **\`${ evaluate(expression) }\`**`; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment