This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluateMath.js
51 lines (44 loc) · 1.33 KB
/
evaluateMath.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Evaluates simple math expression under caret
*/
if (typeof module === 'object' && typeof define !== 'function') {
var define = function (factory) {
module.exports = factory(require, exports, module);
};
}
define(function(require, exports, module) {
var actionUtils = require('../utils/action');
var utils = require('../utils/common');
var math = require('../utils/math');
var range = require('../assets/range');
return {
/**
* Evaluates math expression under the caret
* @param {IEmmetEditor} editor
* @return {Boolean}
*/
evaluateMathAction: function(editor) {
var content = editor.getContent();
var chars = '.+-*/\\';
/** @type Range */
var sel = range(editor.getSelectionRange());
if (!sel.length()) {
sel = actionUtils.findExpressionBounds(editor, function(ch) {
return utils.isNumeric(ch) || chars.indexOf(ch) != -1;
});
}
if (sel && sel.length()) {
var expr = sel.substring(content);
// replace integral division: 11\2 => Math.round(11/2)
expr = expr.replace(/([\d\.\-]+)\\([\d\.\-]+)/g, 'round($1/$2)');
try {
var result = utils.prettifyNumber(math.evaluate(expr));
editor.replaceContent(result, sel.start, sel.end);
editor.setCaretPos(sel.start + result.length);
return true;
} catch (e) {}
}
return false;
}
};
});