simplify init

This commit is contained in:
Mahdi Dibaiee
2015-04-21 16:57:18 +04:30
parent 6e79cb1e83
commit 743220aa1d
7 changed files with 130 additions and 80 deletions

View File

@ -74,5 +74,5 @@ export const flatten = (arr) => {
};
export const removeSymbols = string => {
return string.replace(/\W/g, '');
return string.toString().replace(/\W/g, '');
};

View File

@ -30,6 +30,7 @@ let Equation = {
return stack;
},
/**
* Creates an equation function which replaces variables
* in the given expression with the values specified in order,
@ -49,9 +50,7 @@ let Equation = {
let variables = [];
stack.forEach(a => {
if (typeof a === 'string' && !_.isNumber(a) &&
!operators[a] && a === a.toLowerCase()) {
// grouped variables like (y) need to have their parantheses removed
if (isVariable(a)) {
variables.push(_.removeSymbols(a));
}
});
@ -69,6 +68,31 @@ let Equation = {
};
},
/**
* Simplifies a math expression
*
* Example:
* 2*x^2 + x - 2*x - x^2
* becomes
* x^2 - x
*
* @param {String} expression
* The expression to create an equation for (containing variables)
* @return {String}
* The simplified expression
*/
simplify(expression) {
let stack = parseExpression(expression);
stack = sortStack(stack);
stack = _.parseNumbers(stack);
console.dir(stack, {
depth: null
});
return expression;
},
registerOperator(key, options) {
operators[key] = options;
},
@ -142,6 +166,12 @@ const parseExpression = expression => {
return parseGroups(stack);
};
const isVariable = char => {
let ch = _.removeSymbols(char);
return typeof ch === 'string' && !_.isNumber(ch) &&
!operators[ch] && char === ch.toLowerCase();
};
/**
* Takes the parsed array from parseExpression and
* groups up expressions in parantheses in deep arrays