Navigation Menu

Skip to content

Commit

Permalink
Allow negative array get
Browse files Browse the repository at this point in the history
  • Loading branch information
roya0045 committed Nov 9, 2020
1 parent 5b73ae2 commit 9543350
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
7 changes: 5 additions & 2 deletions resources/function_help/json/array_get
@@ -1,8 +1,11 @@
{
"name": "array_get",
"type": "function",
"description": "Returns the Nth value (0 for the first one) of an array.",
"description": "Returns the Nth value (0 for the first one) or the last -Nth value (-1 for the last one) of an array.",
"arguments": [ {"arg":"array","description":"an array"},
{"arg":"index","description":"the index to get (0 based)"}],
"examples": [ { "expression":"array_get(array('a','b','c'),1)", "returns":"'b'"}]
"examples": [
{ "expression":"array_get(array('a','b','c'),1)", "returns":"'b'"},
{ "expression":"array_get(array('a','b','c'),-1)", "returns":"'c'"}
]
}
3 changes: 2 additions & 1 deletion src/core/expression/qgsexpressionfunction.cpp
Expand Up @@ -5229,7 +5229,8 @@ static QVariant fcnArrayGet( const QVariantList &values, const QgsExpressionCont
{
const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
const int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
if ( pos < 0 || pos >= list.length() ) return QVariant();
if ( pos >= list.length() ) return QVariant();
if ( pos < 0 && ( list.size() + pos ) >= 0 ) return list.at( list.size() + pos );
return list.at( pos );
}

Expand Down
4 changes: 3 additions & 1 deletion tests/src/core/testqgsexpression.cpp
Expand Up @@ -3326,7 +3326,9 @@ class TestQgsExpression: public QObject

QCOMPARE( QgsExpression( "array_get(\"ints\", 1)" ).evaluate( &context ), QVariant( -2 ) );
QCOMPARE( QgsExpression( "array_get(\"ints\", 2)" ).evaluate( &context ), QVariant() );
QCOMPARE( QgsExpression( "array_get(\"ints\", -1)" ).evaluate( &context ), QVariant() );
QCOMPARE( QgsExpression( "array_get(\"ints\", -1)" ).evaluate( &context ), QVariant( -2 ) );
QCOMPARE( QgsExpression( "array_get(\"ints\", -2)" ).evaluate( &context ), QVariant( 1 ) );
QCOMPARE( QgsExpression( "array_get(\"ints\", -3)" ).evaluate( &context ), QVariant() );

QVariantList appendExpected = array;
appendExpected << 3;
Expand Down

0 comments on commit 9543350

Please sign in to comment.