Skip to content
This repository has been archived by the owner on Jun 29, 2019. It is now read-only.

Commit

Permalink
Plugin: Math - Support European-style decimal separator (#268)
Browse files Browse the repository at this point in the history
* Plugin: Math

* Autodetect input mode - UK-style decimal separator "." (current) or European-style decimal separator "," (new) - and ensure the calculation and output matches what the user expects.

Follows the suggested implementation from the MathJS library documentation: http://mathjs.org/examples/browser/custom_separators.html.html

* * Run eslint
  • Loading branch information
dannya authored Jun 10, 2018
1 parent 3f4f5c0 commit 2a289bd
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions app/main/plugins/hain-plugin-math/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ const lo_has = require('lodash.has');

const math = require('mathjs');

const DECIMAL_SEPARATOR_UK = '.';
const DECIMAL_SEPARATOR_EUROPE = ',';

module.exports = (context) => {
const app = context.app;
const clipboard = context.clipboard;
Expand All @@ -29,22 +32,50 @@ module.exports = (context) => {

function makeResultItem(titleKey, query, answer) {
const result = {};
result[titleKey] = `${query.trim()} = ${answer}`;
result[titleKey] = `${query.trim()} = <b>${answer}</b>`;
result.group = 'Math';
result.payload = answer;
return result;
}

function calculate(query, showRedundantResult) {
function calculate(rawQuery, showRedundantResult) {
try {
let query = rawQuery;

// determine input mode by the presence of European-style decimal separators
let inputMode = DECIMAL_SEPARATOR_UK;

if (query.includes(DECIMAL_SEPARATOR_EUROPE)) {
inputMode = DECIMAL_SEPARATOR_EUROPE;

// replace European-style decimal separators with UK-style decimal separators as required by the MathJS library:
// http://mathjs.org/examples/browser/custom_separators.html.html
query = query.replace(
new RegExp(DECIMAL_SEPARATOR_EUROPE, 'g'),
DECIMAL_SEPARATOR_UK
);
}

// calculate value by passing the query into MathJS
const ans = math.eval(query);

if (
lo_isNumber(ans) ||
lo_isString(ans) ||
(lo_isObject(ans) && lo_has(ans, 'value'))
) {
const ansString = Number.parseFloat(ans.toPrecision(10)).toString();
let ansString = Number.parseFloat(ans.toPrecision(10)).toString();
const isResultMeaningful = ansString.trim() !== query.trim();

// if the input mode is the non-standard European-style, take the UK-style output of MathJS and transform it
// back into the European-style that the user expects
if (inputMode === DECIMAL_SEPARATOR_EUROPE && ansString.includes('.')) {
ansString = ansString.replace(
new RegExp(`\\${DECIMAL_SEPARATOR_UK}`, 'g'),
DECIMAL_SEPARATOR_EUROPE
);
}

if (isResultMeaningful || showRedundantResult) return ansString;
}
} catch (e) {}
Expand Down

0 comments on commit 2a289bd

Please sign in to comment.