Skip to content

Commit

Permalink
Merge pull request #873 from antoineveldhoven/spaceship
Browse files Browse the repository at this point in the history
Add support for spaceship operator
  • Loading branch information
RobLoach committed Nov 6, 2023
2 parents 00a6aff + 9f913e0 commit f2bd93e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/twig.expression.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,9 @@ module.exports = function (Twig) {
},
{
type: Twig.expression.type.operator.binary,
// Match any of ??, ?:, +, *, /, -, %, ~, <, <=, >, >=, !=, ==, **, ?, :, and, b-and, or, b-or, b-xor, in, not in
// Match any of ??, ?:, +, *, /, -, %, ~, <=>, <, <=, >, >=, !=, ==, **, ?, :, and, b-and, or, b-or, b-xor, in, not in
// and, or, in, not in, matches, starts with, ends with can be followed by a space or parenthesis
regex: /(^\?\?|^\?:|^(b-and)|^(b-or)|^(b-xor)|^[+\-~%?]|^[:](?!\d\])|^[!=]==?|^[!<>]=?|^\*\*?|^\/\/?|^(and)[(|\s+]|^(or)[(|\s+]|^(in)[(|\s+]|^(not in)[(|\s+]|^(matches)|^(starts with)|^(ends with)|^\.\.)/,
regex: /(^\?\?|^\?:|^(b-and)|^(b-or)|^(b-xor)|^[+\-~%?]|^(<=>)|^[:](?!\d\])|^[!=]==?|^[!<>]=?|^\*\*?|^\/\/?|^(and)[(|\s+]|^(or)[(|\s+]|^(in)[(|\s+]|^(not in)[(|\s+]|^(matches)|^(starts with)|^(ends with)|^\.\.)/,
next: Twig.expression.set.expressions,
transform(match, tokens) {
switch (match[0]) {
Expand Down
9 changes: 9 additions & 0 deletions src/twig.expression.operator.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ module.exports = function (Twig) {
token.associativity = Twig.expression.operator.leftToRight;
break;

case '<=>':
token.precidence = 9;
token.associativity = Twig.expression.operator.leftToRight;
break;

case '<':
case '<=':
case '>':
Expand Down Expand Up @@ -275,6 +280,10 @@ module.exports = function (Twig) {
stack.push(!Twig.lib.boolval(b));
break;

case '<=>':
stack.push(a === b ? 0 : (a < b ? -1 : 1));
break;

case '<':
stack.push(a < b);
break;
Expand Down
7 changes: 7 additions & 0 deletions test/test.expressions.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,13 @@ describe('Twig.js Expressions ->', function () {
{a: false, b: true},
{a: false, b: false}
];
it('should support spaceship operator', function () {
const testTemplate = twig({data: '{{ a <=> b }}'});
numericTestData.forEach(pair => {
const output = testTemplate.render(pair);
output.should.equal((pair.a === pair.b ? 0 : (pair.a < pair.b ? -1 : 1)).toString());
});
});
it('should support less then', function () {
const testTemplate = twig({data: '{{ a < b }}'});
numericTestData.forEach(pair => {
Expand Down

0 comments on commit f2bd93e

Please sign in to comment.