From 9f913e07cc8eb76dd55505a2ac85a43a0483c0b6 Mon Sep 17 00:00:00 2001 From: Antoine Veldhoven Date: Wed, 11 Oct 2023 20:49:54 +0200 Subject: [PATCH] Add support for spaceship operator. --- src/twig.expression.js | 4 ++-- src/twig.expression.operator.js | 9 +++++++++ test/test.expressions.js | 7 +++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/twig.expression.js b/src/twig.expression.js index 80a8b4dc..0e2ea9f2 100644 --- a/src/twig.expression.js +++ b/src/twig.expression.js @@ -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]) { diff --git a/src/twig.expression.operator.js b/src/twig.expression.operator.js index 452add4e..027382e1 100644 --- a/src/twig.expression.operator.js +++ b/src/twig.expression.operator.js @@ -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 '>': @@ -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; diff --git a/test/test.expressions.js b/test/test.expressions.js index fb414283..6620479a 100644 --- a/test/test.expressions.js +++ b/test/test.expressions.js @@ -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 => {