Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

50 changes: 44 additions & 6 deletions src/expression/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,19 @@ export const createParse = /* #__PURE__ */ factory(name, dependencies, ({
return node
}

function isPurePercentageExpression (n) {
if (!n) return false
if (n.isPercentage) return true
if (n.type === 'ParenthesisNode') return isPurePercentageExpression(n.content)
if (isOperatorNode(n) && (n.fn === 'unaryPlus' || n.fn === 'unaryMinus') && n.args && n.args.length === 1) {
return isPurePercentageExpression(n.args[0])
}
if (isOperatorNode(n) && (n.fn === 'add' || n.fn === 'subtract') && n.args && n.args.length === 2) {
return isPurePercentageExpression(n.args[0]) && isPurePercentageExpression(n.args[1])
}
return false
}

/**
* Parse a block with expressions. Expressions can be separated by a newline
* character '\n', or by a semicolon ';'. In case of a semicolon, no output
Expand Down Expand Up @@ -1028,8 +1041,13 @@ export const createParse = /* #__PURE__ */ factory(name, dependencies, ({
fn = operators[name]

getTokenSkipNewline(state)
const savedPrefer = state.preferUnaryPercentAfterPlus
if (isPurePercentageExpression(node)) {
state.preferUnaryPercentAfterPlus = true
}
const rightNode = parseMultiplyDivideModulus(state)
if (rightNode.isPercentage) {
state.preferUnaryPercentAfterPlus = savedPrefer
if ((rightNode.isPercentage || isPurePercentageExpression(rightNode)) && !isPurePercentageExpression(node)) {
params = [node, new OperatorNode('*', 'multiply', [node, rightNode])]
} else {
params = [node, rightNode]
Expand Down Expand Up @@ -1169,17 +1187,37 @@ export const createParse = /* #__PURE__ */ factory(name, dependencies, ({
* @return {Node} node
* @private
*/
function parseUnaryPercentage (state) {
function parseUnaryPercentage (state, lookaheadMode) {
let node = parseUnary(state)

if (state.token === '%') {
const previousState = Object.assign({}, state)
getTokenSkipNewline(state)
if (state.preferUnaryPercentAfterPlus && (state.token === '+' || state.token === '-')) {
node = new OperatorNode('/', 'divide', [node, new ConstantNode(100)], false, true)
return node
}
if (lookaheadMode) {
node = new OperatorNode('/', 'divide', [node, new ConstantNode(100)], false, true)
return node
}
// We need to decide if this is a unary percentage % or binary modulo %
// So we attempt to parse a unary expression at this point.
// If it fails, then the only possibility is that this is a unary percentage.
// If it succeeds, then we presume that this must be binary modulo, since the
// only things that parseUnary can handle are _higher_ precedence than unary %.
// So we attempt a controlled lookahead only for + or - to support cases like
// 10% + 20% and 10% + (20% + 30%).
if (state.token === '+' || state.token === '-') {
const lookAheadState = Object.assign({}, state)
getTokenSkipNewline(lookAheadState)
try {
const laNode = parseUnaryPercentage(lookAheadState, true)
if (isPurePercentageExpression(laNode)) {
node = new OperatorNode('/', 'divide', [node, new ConstantNode(100)], false, true)
return node
}
} catch (err) {
node = new OperatorNode('/', 'divide', [node, new ConstantNode(100)], false, true)
return node
}
}
try {
parseUnary(state)
// Not sure if we could somehow use the result of that parseUnary? Without
Expand Down
58 changes: 58 additions & 0 deletions test/unit-tests/expression/parse.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1668,6 +1668,59 @@ describe('parse', function () {
assert.strictEqual(parseAndEval('3%+100'), 3) // treat as 3 mod 100
})

it('should add and subtract percentages intuitively', function () {
approxEqual(parseAndEval('10% + 20%'), 0.3)
approxEqual(parseAndEval('10% - 20%'), -0.1)
approxEqual(parseAndEval('10% + 20% + 30%'), 0.6)
approxEqual(parseAndEval('10% + 50% - 20%'), 0.4)
})

it('should preserve relative percentage on numbers', function () {
approxEqual(parseAndEval('50 + 20% + 10%'), 66)
})

it('should compound percentages on variables', function () {
const scope = { x: 10 }
approxEqual(parseAndEval('x + 20% + 10%', scope), 13.2)
approxEqual(parseAndEval('x - 10% - 20%', scope), 7.2)
})

it('should keep percent sums before adding a variable', function () {
const scope = { x: 1 }
approxEqual(parseAndEval('10% + 20% + x', scope), 1.3)
approxEqual(parseAndEval('10% - 20% - x', scope), -1.1)
})

it('should support parentheses with percentages', function () {
approxEqual(parseAndEval('(10%) + (20%)'), 0.3)
approxEqual(parseAndEval('10% + (20%)'), 0.3)
approxEqual(parseAndEval('(10% + 20%) + 30%'), 0.6)
approxEqual(parseAndEval('10% + (20% + 30%)'), 0.6)
})

it('should add more pure percentages arithmetically', function () {
approxEqual(parseAndEval('50% + 20%'), 0.7)
approxEqual(parseAndEval('10% + 20% - 30%'), 0.0)
approxEqual(parseAndEval('10% + 20% + 30% + 40%'), 1.0)
})

it('should combine percentages inside multiplication and with parentheses', function () {
const scope = { x: 10 }
approxEqual(parseAndEval('x * (10% + 20%)', scope), 3)
approxEqual(parseAndEval('(10% + 20%) * x', scope), 3)
approxEqual(parseAndEval('x * 10% * 20%', scope), 0.2)
})

it('should preserve semantics when grouping percentage additions explicitly', function () {
approxEqual(parseAndEval('50 + (20% + 10%)'), 65)
const scope = { x: 100 }
approxEqual(parseAndEval('x + (20% + 10%)', scope), 130)
})

it('should support units with percentages on the right-hand side', function () {
approxDeepEqual(parseAndEval('10 cm + 20%'), new Unit(12, 'cm'))
})

it('should parse unary % with subtraction', function () {
approxEqual(parseAndEval('100-3%'), 97)
assert.strictEqual(parseAndEval('3%-100'), -97) // treat as 3 mod -100
Expand All @@ -1678,6 +1731,11 @@ describe('parse', function () {
assert.strictEqual(parseAndEval('11%~-3'), 1) // equivalent to 11 mod 2
})

it('should interpret modulo vs percent in mixed sums symmetrically', function () {
approxEqual(parseAndEval('10% + 20 % 3'), 2.1)
approxEqual(parseAndEval('20 % 3 + 10%'), 2.2)
})

it('should parse operator mod', function () {
approxEqual(parseAndEval('8 mod 3'), 2)
})
Expand Down