Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some additional helper functions #7

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions lib/__test__/__snapshots__/query.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,76 @@ exports[`query getVariableFactors 2x 1`] = `
]
`;

exports[`query getVariableFactors 2x^2 * y 1`] = `
[
{
"type": "Apply",
"op": "pow",
"args": [
{
"type": "Identifier",
"name": "x"
},
{
"value": "2",
"type": "Number"
}
]
},
{
"type": "Identifier",
"name": "y"
}
]
`;

exports[`query getVariableFactors 2x^2 * z^2 + y^3 1`] = `
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

y^3 is not a factor, it's a term. If you want a function that finds all variable factors we should have a separate function for that.

[
{
"type": "Apply",
"op": "pow",
"args": [
{
"type": "Identifier",
"name": "x"
},
{
"value": "2",
"type": "Number"
}
]
},
{
"type": "Apply",
"op": "pow",
"args": [
{
"type": "Identifier",
"name": "z"
},
{
"value": "2",
"type": "Number"
}
]
},
{
"type": "Apply",
"op": "pow",
"args": [
{
"type": "Identifier",
"name": "y"
},
{
"value": "3",
"type": "Number"
}
]
}
]
`;

exports[`query getVariableFactors 2x^2 1`] = `
[
{
Expand Down
2 changes: 2 additions & 0 deletions lib/__test__/query.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ describe('query', () => {
'x^2',
'2x^2',
'2 x y z',
'2x^2 * y',
'2x^2 * z^2 + y^3'
])

suite('getCoefficientsAndConstants', query.getCoefficientsAndConstants, [
Expand Down
11 changes: 5 additions & 6 deletions lib/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,17 +174,16 @@ export const getCoefficient = (node) => {
}
}

export const getVariableFactors = (node) => {
export const getVariableFactors = (node, factors = []) => {
if (isVariableFactor(node)) {
return [node]
} else if (isMul(node)) {
return node.args.filter(isVariableFactor)
factors.push(node)
} else if (isApply(node)) {
node.args.forEach(arg => getVariableFactors(arg, factors))
} else if (isNeg(node)) {
// TODO: figure out how to handle (x)(-y)(z)
return getVariableFactors(node.args[0])
} else {
return []
}
return factors
}

export const getVariableFactorName = (node) => {
Expand Down