Skip to content

Commit 9f913e0

Browse files
committedOct 11, 2023
Add support for spaceship operator.
1 parent 00a6aff commit 9f913e0

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed
 

‎src/twig.expression.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -212,9 +212,9 @@ module.exports = function (Twig) {
212212
},
213213
{
214214
type: Twig.expression.type.operator.binary,
215-
// Match any of ??, ?:, +, *, /, -, %, ~, <, <=, >, >=, !=, ==, **, ?, :, and, b-and, or, b-or, b-xor, in, not in
215+
// Match any of ??, ?:, +, *, /, -, %, ~, <=>, <, <=, >, >=, !=, ==, **, ?, :, and, b-and, or, b-or, b-xor, in, not in
216216
// and, or, in, not in, matches, starts with, ends with can be followed by a space or parenthesis
217-
regex: /(^\?\?|^\?:|^(b-and)|^(b-or)|^(b-xor)|^[+\-~%?]|^[:](?!\d\])|^[!=]==?|^[!<>]=?|^\*\*?|^\/\/?|^(and)[(|\s+]|^(or)[(|\s+]|^(in)[(|\s+]|^(not in)[(|\s+]|^(matches)|^(starts with)|^(ends with)|^\.\.)/,
217+
regex: /(^\?\?|^\?:|^(b-and)|^(b-or)|^(b-xor)|^[+\-~%?]|^(<=>)|^[:](?!\d\])|^[!=]==?|^[!<>]=?|^\*\*?|^\/\/?|^(and)[(|\s+]|^(or)[(|\s+]|^(in)[(|\s+]|^(not in)[(|\s+]|^(matches)|^(starts with)|^(ends with)|^\.\.)/,
218218
next: Twig.expression.set.expressions,
219219
transform(match, tokens) {
220220
switch (match[0]) {

‎src/twig.expression.operator.js

+9
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@ module.exports = function (Twig) {
9393
token.associativity = Twig.expression.operator.leftToRight;
9494
break;
9595

96+
case '<=>':
97+
token.precidence = 9;
98+
token.associativity = Twig.expression.operator.leftToRight;
99+
break;
100+
96101
case '<':
97102
case '<=':
98103
case '>':
@@ -275,6 +280,10 @@ module.exports = function (Twig) {
275280
stack.push(!Twig.lib.boolval(b));
276281
break;
277282

283+
case '<=>':
284+
stack.push(a === b ? 0 : (a < b ? -1 : 1));
285+
break;
286+
278287
case '<':
279288
stack.push(a < b);
280289
break;

‎test/test.expressions.js

+7
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,13 @@ describe('Twig.js Expressions ->', function () {
173173
{a: false, b: true},
174174
{a: false, b: false}
175175
];
176+
it('should support spaceship operator', function () {
177+
const testTemplate = twig({data: '{{ a <=> b }}'});
178+
numericTestData.forEach(pair => {
179+
const output = testTemplate.render(pair);
180+
output.should.equal((pair.a === pair.b ? 0 : (pair.a < pair.b ? -1 : 1)).toString());
181+
});
182+
});
176183
it('should support less then', function () {
177184
const testTemplate = twig({data: '{{ a < b }}'});
178185
numericTestData.forEach(pair => {

0 commit comments

Comments
 (0)
Please sign in to comment.