Last active
January 4, 2021 17:10
-
-
Save vekMaster/117c5cb2219f1ff75665df08caaa7e0c to your computer and use it in GitHub Desktop.
Get each monomial from a polynomial, with its power
This file contains 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
/** | |
Based on | |
https://stackoverflow.com/questions/50035160/extract-variables-coeffcients-powers-from-a-polynomial-string-javascript#answers | |
*/ | |
function extractPolynomial(polynomialStr) { | |
let arr = []; | |
const eachMono = polynomialStr.match(/[+-]?\d*(x|y)(\^\d)*((y|x)(\^\d)*)*(\(([^()]*|\(([^()]*|\([^()]*\))*\))*\))?|[+-\s]\d+(\(([^()]*|\(([^()]*|\([^()]*\))*\))*\))?/g); | |
eachMono.forEach((match) => { | |
const monomium = match.match(/([a-z]\^\d|[a-z])/gi) ? match.match(/([a-z]\^\d|[a-z])/gi).join("") : " "; | |
const coeff = parseFloat(match.split(monomium)[0]) || 1; | |
let power = 1; | |
let variableValues = { variable: "", power: 0 }; | |
if (monomium != " ") { | |
let tempVars = monomium.match(/([a-z]\^\d|[a-z])/gi); | |
for (let i = 0; i < tempVars.length; i++) { | |
variableValues.variable = tempVars[i].match(/[a-z]/gi)[0]; | |
let tempV = tempVars[i].split("^"); | |
if (tempV.length > 1) { | |
variableValues.power = parseFloat(tempV[1]); | |
} else { | |
variableValues.power = 1; | |
} | |
} | |
} | |
arr.push({ | |
coeff: coeff, | |
variableValues: variableValues | |
}); | |
}); | |
return arr; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment