Skip to content
Permalink
Browse files

Merge pull request #39921 from roya0045/negative_array_Get

[Feature][Expression]Negative array get
  • Loading branch information
m-kuhn committed Nov 17, 2020
2 parents d303a6b + a36de09 commit aeb9463b47a7a4ec0335562b6d7d800b22bb43e4
@@ -2,8 +2,11 @@
"name": "array_get",
"type": "function",
"groups": ["Arrays"],
"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'"}
]
}
@@ -5324,8 +5324,10 @@ 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();
return list.at( pos );
if ( pos < list.length() && pos >= 0 ) return list.at( pos );
else if ( pos < 0 && ( list.length() + pos ) >= 0 )
return list.at( list.length() + pos );
return QVariant();
}

static QVariant fcnArrayFirst( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
@@ -3333,7 +3333,8 @@ class TestQgsExpression: public QObject

QCOMPARE( QgsExpression( "array_get(\"strings\", 1)" ).evaluate( &context ), QVariant( "two" ) );
QCOMPARE( QgsExpression( "array_get(\"strings\", 2)" ).evaluate( &context ), QVariant() );
QCOMPARE( QgsExpression( "array_get(\"strings\", -1)" ).evaluate( &context ), QVariant() );
QCOMPARE( QgsExpression( "array_get(\"strings\", -1)" ).evaluate( &context ), QVariant( "two" ) );
QCOMPARE( QgsExpression( "array_get(\"strings\", -4)" ).evaluate( &context ), QVariant() );

QStringList appendExpected = array;
appendExpected << QStringLiteral( "three" );
@@ -3409,7 +3410,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;

0 comments on commit aeb9463

Please sign in to comment.
You can’t perform that action at this time.