simplify init
This commit is contained in:
@ -74,5 +74,5 @@ export const flatten = (arr) => {
|
||||
};
|
||||
|
||||
export const removeSymbols = string => {
|
||||
return string.replace(/\W/g, '');
|
||||
return string.toString().replace(/\W/g, '');
|
||||
};
|
||||
|
36
lib/index.js
36
lib/index.js
@ -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
|
||||
|
Reference in New Issue
Block a user