Coleção
The Collection class manages Collection type variables.
A collection is initialized with:
New collection {( ...value : any )} : Collection
|
New shared collection {( ...value : any )} : Collection
|
Exemplo
var $colVar : Collection //creation of collection type 4D variable
$colVar:=New collection //initialization of the collection and assignment to the 4D variable
Resumo
New collection
New collection {( ...value : any )} : Collection
Parameter | Type | Descrição | |
---|---|---|---|
value | Number, Text, Date, Time, Boolean, Object, Collection, Picture, Pointer | -> | Valor(es) de collection |
Resultado | Coleção | <- | New collection |
Descrição
O comando Nova coleção
cria uma nova coleção vazia ou pré-completada e devolve sua referência.
Se não passar nenhum parâmetro, New collection
cria uma coleção vazia e retorna sua referência.
Precisa atribuir a referência devolvida à uma variável 4D de tipo Collection.
Keep in mind that
var : Collection
orC_COLLECTION
statements declare a variable of theCollection
type but does not create any collection.
Opcionalmente pode pré-preencher a nova coleção passando um ou mais parâmetros value.
Pode também adicionar ou modificar elementos subsequentemente através de assignação. Por exemplo:
myCol[10]:="My new element"
Se o novo índice de elemento estiver além do último elemento existente da coleção, a coelção é redimensionada automaticamente e todos os elementos intermediários são atribuídos ao valor null.
Pode passar qualquer número de valores de qualquer tipo compatível (número, texto, data, imagem, ponteiro, objeto, coleção....). Diferente de arrays, coleções podem misturar dados de tipos diferentes.
Pode prestar atenção aos problemas de conversão abaixo:
- If you pass a pointer, it is kept "as is"; it is evaluated using the
JSON Stringify
command - Dates are stored as "yyyy-mm-dd" dates or strings with the "YYYY-MM-DDTHH:mm:ss.SSSZ" format, according to the current "dates inside objects" database setting. When converting 4D dates into text prior to storing them in the collection, by default the program takes the local time zone into account. You can modify this behavior using the
Dates inside objects
selector of theSET DATABASE PARAMETER
command. - If you pass a time, it is stored as a number of milliseconds (Real).
Exemplo 1
Se quiser criar uma nova coleção vazia e atribuí-la à uma variável coleção 4D:
var $myCol : Collection
$myCol:=New collection
//$myCol=[]
Exemplo 2
Se quiser criar uma coleção pré-prenchida:
var $filledColl : Collection
$filledColl:=New collection(33;"mike";"november";->myPtr;Current date)
//$filledColl=[33,"mike","november","->myPtr","2017-03-28T22:00:00.000Z"]
Exemplo 3
Pode criar uma nova coleção e adicionar um novo elemento:
var $coll : Collection
$coll:=New collection("a";"b";"c")
//$coll=["a","b","c"]
$coll[9]:="z" //add a 10th element with value "z"
$vcolSize:=$coll.length //10
//$coll=["a","b","c",null,null,null,null,null,null,"z"]
New shared collection
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
New shared collection {( ...value : any )} : Collection
Parameter | Type | Descrição | |
---|---|---|---|
value | Number, Text, Date, Time, Boolean, Shared object, Shared collection | -> | Valores da collection compartida |
Resultado | Coleção | <- | New shared collection |
Descrição
O comando New shared collection
cria uma nova coleção vazia ou pré-preenchida partilhada e retorna sua referência.
Adicionar um elemento para essa coleção deve ser rodeada pela estrutura Use... End
, senão um erro é gerado. Ler um elemento sem a estrutura é entretanto possível.
For more information on shared collections, please refer to the Shared objects and collections page.
Se não quiser passar parâmetros, New shared collection
cria uma coleção vazia partilhada e retorna sua referência.
Precisa atribuir a referência devolvida à uma variável 4D de tipo Collection.
Keep in mind that
var : Collection
orC_COLLECTION
statements declare a variable of theCollection
type but does not create any collection.
Opcionalmente pode preencher automaticamente a nova coleção partilhada passando um ou vários valorescomo parâmetros. Também pode adicionar ou modificar elementos através de atribuição de notação de objetos (ver exemplo).
Se o novo índice elemento for além do último elemento existente da coleção partilhada, a coleção é automaticamente redimensionada e todos os novos elementos intermediários são atribuídos um valornull.
Pode passar qualquer número de valores dos tipos compatíveis abaixo:
- number (real, longint...). Number values are always stored as reals.
- texto
- booleano
- date
- time (stored as number of milliseconds - real)
- null
- shared object(*)
- shared collection(*) > Unlike standard (not shared) collections, shared collections do not support pictures, pointers, and objects or collections that are not shared.
Unlike standard (not shared) collections, shared collections do not support pictures, pointers, and objects or collections that are not shared.
(*)Quando um objeto partilhado ou coleção forem adicionadas a uma coleção partilhada, partilham o mesmo locking identifier. Para saber mais sobre esse ponto, veja o guia 4D Developer'.
Exemplo
$mySharedCol:=New shared collection("alpha";"omega")
Use($mySharedCol)
$mySharedCol[1]:="beta"
End use
.average()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.average( {propertyPath : Text } ) : Real
Parameter | Type | Descrição | |
---|---|---|---|
propertyPath | Texto | -> | Rota de propriedade objeto a ser usado para cálculos |
Resultado | Real, Undefined | <- | Média aritmética dos valores coleção |
Descrição
A função .average()
retorna a média aritmética de valores definidos da instância da collection.
Apenas elementos numéricos são considerados para cálculos (outros tipos são ignorados).
Se a coleção contiver objetos, passe o parâmetro propertyPath para indicar a propriedade objeto para levar em consideração.
.average()
retorna undefined
se:
- the collection is empty,
- the collection does not contain numerical elements,
- propertyPath is not found in the collection.
Exemplo 1
var $col : Collection
$col:=New collection(10;20;"Monday";True;6)
$vAvg:=$col.average() //12
Exemplo 2
var $col : Collection
$col:=New collection
$col.push(New object("name";"Smith";"salary";10000))
$col.push(New object("name";"Wesson";"salary";50000))
$col.push(New object("name";"Gross";"salary";10500))
$vAvg:=$col.average("salary") //23500
.clear()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.clear() : Collection
Parameter | Type | Descrição | |
---|---|---|---|
Resultado | Coleção | <- | Collection original com todos os elementos removidos |
Descrição
A função .clear()
remove todos os elementos da instância collection e retorna uma collection vazia.
This function modifies the original collection.
Exemplo
var $col : Collection
$col:=New collection(1;2;5)
$col.clear()
$vSize:=$col.length //$vSize=0
.combine()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.combine( col2 : Collection {; index : Integer } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
col2 | Coleção | -> | Collection a combinar |
index | Integer | -> | Posição para a qual inserir elementos para combinar em coleção (padrão = length +1) |
Resultado | Coleção | <- | Collection original contendo elementos combinados |
Descrição
A função .concat()
retorna uma nova coleção contendo os elementos da coleção original com todos os elementos do parâmetro value adicionado ao final.
This function modifies the original collection.
Como padrão, elementos col2 são adicionados ao final da collection original. Pode passar em index a posição onde quiser que os elmentos col2 sejam inseridos na coleção.
Warning: Keep in mind that collection elements are numbered from 0.
- If index > the length of the collection, the actual starting index will be set to the length of the collection.
- If index < 0, it is recalculated as index:=index+length (it is considered as the offset from the end of the collection).
- If the calculated value is negative, index is set to 0.
Exemplo
var $c; $fruits : Collection
$c:=New collection(1;2;3;4;5;6)
$fruits:=New collection("Orange";"Banana";"Apple";"Grape")
$c.combine($fruits;3) //[1,2,3,"Orange","Banana","Apple","Grape",4,5,6]
.concat()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.concat( value : any { ;...valueN } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
value | Number, Text, Object, Collection, Date, Time, Boolean, Picture | -> | Valores a concatenar. Se value for uma coleção, todos os elementos da coleção são adicionados para a coleção original |
Resultado | Coleção | <- | Nova coleção com valores adicionados à coleção original |
Descrição
As fórmulas não tem compatibilidade com a função collection.query()
, nem com o parâmetro queryString nem como parâmetro do objeto fórmula.
This function does not modify the original collection.
Se value for uma coleção, todos os elementos são adicionados como novos elementos no final da coleção original. Se value não for a coleção, será adicionado ao novo elemento.
Exemplo
var $c : Collection
$c:=New collection(1;2;3;4;5)
$fruits:=New collection("Orange";"Banana";"Apple";"Grape")
$fruits.push(New object("Intruder";"Tomato"))
$c2:=$c.concat($fruits) //[1,2,3,4,5,"Orange","Banana","Apple","Grape",{"Intruder":"Tomato"}]
$c2:=$c.concat(6;7;8) //[1,2,3,4,5,6,7,8]
.copy()
Histórico
Versão | Mudanças |
---|---|
v18 R3 | New ck shared option. New groupWith parameters |
v16 R6 | Adicionado |
.copy() : Collection
.copy( option : Integer ) : Collection
.copy( option : Integer ; groupWithCol : Collection ) : Collection
.copy( option : Integer ; groupWithObj : Object ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
option | Integer | -> | ck resolve pointers : resolve ponteiros antes de copiar,ck shared : retorna uma coleção partilihada |
groupWithCol | Coleção | -> | Coleção partilhada a ser agrupada com a coleção resultante |
groupWithObj | Objeto | -> | Objeto partilhado a ser agrupado com a coleção resultante |
Resultado | Coleção | <- | Cópia profunda da collection original |
Descrição
A função .copy()
retorna uma cópia profunda da instância collection.Deep copy significa que objetos ou collections dentro da coleção original são duplicadas e não partilham qualquer referência com a collection retornada.
This function does not modify the original collection.
Se passado, o parâmetro option pode conter uma das constantes abaixo (ou ambas):
option | Descrição |
---|---|
ck resolve pointers | Se a collection original contém valores tipo ponteiro, por padrão a cópia também contém os ponteiros. Entretanto pode resolver ponteiros quando copiar por passando os ck resolve pointers. Nesse caso, cada ponteiro presenta na coleção é avaliada quando copiar e seu valor de dereferencia é usado. |
ck shared | Como padrão, copy() retorna uma colleciton regular (não partilhado), mesmo se o comando for aplicado para a collection shared. Passe a constante ck shared para criar uma collection shared. Nesse caso, pode usar o parâmetro groupWith para associar a collection partilhada com outra collection ou objeto (ver abaixo). |
Os parâmetros groupWithCol ou groupWithObj permite determinar uma collection ou um objeto com o qual a coleção resultante deveria ser associada.
Exemplo 1
Se quiser copiar a collection comum (não partilhada) $lastnames no objeto partilhado $sharedObject. Para fazer isso, precisa criar uma cópia partilhada da coleção ($sharedLastnames).
var $sharedObject : Object
var $lastnames;$sharedLastnames : Collection
var $text : Text
$sharedObject:=New shared object
$text:=Document to text(Get 4D folder(Current resources folder)+"lastnames.txt")
$lastnames:=JSON Parse($text) //$lastnames is a regular collection
$sharedLastnames:=$lastnames.copy(ck shared) //$sharedLastnames is a shared collection
//Now we can put $sharedLastnames into $sharedObject Use($sharedObject)
$sharedObject.lastnames:=$sharedLastnames End use
Exemplo 2
Se quisermos combinar $sharedColl1 e $sharedColl2. Já que pertencem a grupos partilhados diferentes, uma combinação diferente resultaria em um erro. Por isso precisa fazer uma cópia partilhada de $sharedColl1 e designar $sharedColl2 commo um grupo partilhado para a cópia.
var $sharedColl1;$sharedColl2;$copyColl : Collection
$sharedColl1:=New shared collection(New shared object("lastname";"Smith"))
$sharedColl2:=New shared collection(New shared object("lastname";"Brown"))
//$copyColl belongs to the same shared group as $sharedColl2
$copyColl:=$sharedColl1.copy(ck shared;$sharedColl2)
Use($sharedColl2)
$sharedColl2.combine($copyColl)
End use
Exemplo 3
Se tiver uma collection comum ($lastnames) e se quisermos colocar emStorage da aplicação. Para fazer isso, precisamos criar antes uma cópia partilhada ($sharedLastnames).
var $lastnames;$sharedLastnames : Collection
var $text : Text
$text:=Document to text(Get 4D folder(Current resources folder)+"lastnames.txt")
$lastnames:=JSON Parse($text) //$lastnames is a regular collection
$sharedLastnames:=$lastnames.copy(ck shared) // shared copy Use(Storage)
Storage.lastnames:=$sharedLastnames End use
Exemplo 4
Esse exemplo ilustra o uso da opção ck resolve pointers
:
var $col : Collection
var $p : Pointer
$p:=->$what
$col:=New collection
$col.push(New object("alpha";"Hello";"num";1))
$col.push(New object("beta";"You";"what";$p))
$col2:=$col.copy()
$col2[1].beta:="World!"
ALERT($col[0].alpha+" "+$col2[1].beta) //displays "Hello World!"
$what:="You!"
$col3:=$col2.copy(ck resolve pointers)
ALERT($col3[0].alpha+" "+$col3[1].what) //displays "Hello You!"
.count()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.count( { propertyPath : Text } ) : Real
Parameter | Type | Descrição | |
---|---|---|---|
propertyPath | Texto | -> | Rota de propriedade objeto a ser usado para cálculos |
Resultado | Real | <- | Número de elementos na coleção |
Descrição
A função .count()
retorna o número de elementos não-null na coleção.
Se a coleção conter objetos, pode passar o parâmetro propertyPath. Nesse caso, só elementos que conterem propertyPath serão levados em consideração.
Exemplo
var $col : Collection
var $count1;$count2 : Real
$col:=New collection(20;30;Null;40)
$col.push(New object("name";"Smith";"salary";10000))
$col.push(New object("name";"Wesson";"salary";50000))
$col.push(New object("name";"Gross";"salary";10500))
$col.push(New object("lastName";"Henry";"salary";12000))
$count1:=$col.count() //$count1=7
$count2:=$col.count("name") //$count2=3
.countValues()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.countValues( value : any {; propertyPath : Text } ) : Real
Parameter | Type | Descrição | |
---|---|---|---|
value | Text, Number, Boolean, Date, Object, Collection | -> | Valor a contar |
propertyPath | Texto | -> | Rota de propriedade objeto a ser usado para cálculos |
Resultado | Real | <- | Número de ocorrências do valor |
Descrição
A função .countValues()
retorna o número de vezes que o valor foi encontrado na coleção.
Pode passar em value:
- a scalar value (text, number, boolean, date),
- an object or a collection reference.
Para um elemento ser encontrado, o tipo de value deve ser equivalente ao tipo de elemento, o método usa o operador equality.
O parâmetro opcional propertyPath permite contar valores dentro de uma coleção de objetos: passe em propertyPath a rota da propriedade cujos valores quer contar.
This function does not modify the original collection.
Exemplo 1
var $col : Collection
var $vCount : Integer
$col:=New collection(1;2;5;5;5;3;6;4)
$vCount:=$col.countValues(5) // $vCount=3
Exemplo 2
var $col : Collection
var $vCount : Integer
$col:=New collection
$col.push(New object("name";"Smith";"age";5))
$col.push(New object("name";"Wesson";"age";2))
$col.push(New object("name";"Jones";"age";3))
$col.push(New object("name";"Henry";"age";4))
$col.push(New object("name";"Gross";"age";5))
$vCount:=$col.countValues(5;"age") //$vCount=2
Exemplo 3
var $numbers; $letters : Collection
var $vCount : Integer
$letters:=New collection("a";"b";"c")
$numbers:=New collection(1;2;$letters;3;4;5)
$vCount:=$numbers.countValues($letters) //$vCount=1
.distinct()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.distinct( {option : Integer} ) : Collection
.distinct( propertyPath : Text {; option : Integer } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
option | Integer | -> | ck diacritical : avaliação diacríticos ("A" # "a" por exemplo) |
propertyPath | Texto | -> | Rota do atributo cujos valores quer obter |
Resultado | Coleção | <- | Nova coleção com apenas valores distintos |
Descrição
A função .distinct()
function retorna uma coleção que contém apenas valores distintos (diferentes) da coleção original.
This function does not modify the original collection.
A coleção retornada é ordenada automaticamente. Valores Null não são retornados.
Como padrão, uma avaliação não-diacrítica é realizada. Se quiser que a avaliação diferencie minúsculas de maiúsculas ou que diferencie letras acentuadas, passe a constante ck diacritical
no parâmetrooption.
Se a coleção conter objetos, pode passar o parâmetro propertyPath para indicar a propriedade objeto cujos valores diferentes você quer obter.
Exemplo
var $c; $c2 : Collection
$c:=New collection
$c.push("a";"b";"c";"A";"B";"c";"b";"b")
$c.push(New object("size";1))
$c.push(New object("size";3))
$c.push(New object("size";1))
$c2:=$c.distinct() //$c2=["a","b","c",{"size":1},{"size":3},{"size":1}]
$c2:=$c.distinct(ck diacritical) //$c2=["a","A","b","B","c",{"size":1},{"size":3},{"size":1}]
$c2:=$c.distinct("size") //$c2=[1,3]
.equal()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.equal( collection2 : Collection {; option : Integer } ) : Boolean
Parameter | Type | Descrição | |
---|---|---|---|
collection2 | Coleção | -> | Coleção a comparar |
option | Integer | -> | ck diacritical : avaliação diacríticos ("A" # "a" por exemplo) |
Resultado | Booleano | <- | True se as coleções forem idênticas, senão false |
Descrição
A função .equal()
compara collection com collection2 e retorna true se forem idênticos (comparação profunda/deep comparison).
Como padrão, uma avaliação não-diacrítica é realizada. Se quiser que a avaliação diferencie maiúsculas de minúsculas e caracteres acentuados, passe a constanteck diacritical
no parâmetro option.
Elements with Null values are not equal to Undefined elements.
Exemplo
var $c; $c2 : Collection
var $b : Boolean
$c:=New collection(New object("a";1;"b";"orange");2;3)
$c2:=New collection(New object("a";1;"b";"orange");2;3;4)
$b:=$c.equal($c2) // false
$c:=New collection(New object("1";"a";"b";"orange");2;3)
$c2:=New collection(New object("a";1;"b";"orange");2;3)
$b:=$c.equal($c2) // false
$c:=New collection(New object("a";1;"b";"orange");2;3)
$c2:=New collection(New object("a";1;"b";"ORange");2;3)
$b:=$c.equal($c2) // true
$c:=New collection(New object("a";1;"b";"orange");2;3)
$c2:=New collection(New object("a";1;"b";"ORange");2;3)
$b:=$c.equal($c2;ck diacritical) //false
.every()
Histórico
Versão | Mudanças |
---|---|
v19 R6 | Support of formula |
v16 R6 | Adicionado |
As fórmulas não tem compatibilidade com a função collection.query()
, nem com o parâmetro queryString nem como parâmetro do objeto fórmula.
Parameter | Type | Descrição | |
---|---|---|---|
startFrom | Integer | -> | Índice para início do teste em |
formula | 4D. Function | -> | Formula object |
methodName | Texto | -> | Name of a method |
param | Mixed | -> | Parameter(s) to pass to formula or methodName |
Resultado | Booleano | <- | True se todos os elementos passarem o teste com sucesso |
Descrição
The .every()
function returns true if all elements in the collection successfully passed a test implemented in the provided formula object or methodName name.
You designate the callback to be executed to evaluate collection elements using either:
- formula (recommended syntax), a Formula object that can encapsulate any executable expressions, including functions and project methods;
- or methodName, the name of a project method (text).
The callback is called with the parameter(s) passed in param (optional). The callback can perform any test, with or without the parameter(s) and must return true for every element fulfilling the test. It receives an Object
in first parameter ($1).
The callback receives the following parameters:
- in $1.value: element value to be evaluated
- $2: param
- $N: paramN...
It can set the following parameter(s):
- (mandatory if you used a method) $1.result (Boolean): true if the element value evaluation is successful, false otherwise.
- $1.stop (Booleano, opcional): true para parar o método callback. The returned value is the last calculated.
In all cases, at the point when the .every()
function encounters the first collection element evaluated to false, it stops calling the callback and returns false.
By default, .some()
tests the whole collection. Optionally, you can pass the index of an element from which to start the test in startFrom.
- Se startFrom >= tamanho da coleção, é retornado false, o que significa que a coleção não é testada.
- Se startFrom < 0, é considerada como offset do final da coleção( startFrom:=startFrom+length).
- If startFrom = 0, the whole collection is searched (default).
Exemplo 1
var $c : Collection
$c:=New collection
$c.push(New object("name";"Smith";"dateHired";!22-05-2002!;"age";45))
$c.push(New object("name";"Wesson";"dateHired";!30-11-2017!))
$c.push(New object("name";"Winch";"dateHired";!16-05-2018!;"age";36))
$c.push(New object("name";"Sterling";"dateHired";!10-5-1999!;"age";Null))
$c.push(New object("name";"Mark";"dateHired";!01-01-2002!))
Exemplo 2
Esse exemplo testa que todos os elementos da coleção sejam do tipo real:
var $c : Collection
var $b : Boolean
var $f : 4D. Function
$f:=Formula(Value type($1.value)=$2
$c:=New collection
$c.push(5;3;1;4;6;2)
$b:=$c.every($f;Is real) //$b=true
$c:=$c.push(New object("name";"Cleveland";"zc";35049))
$c:=$c.push(New object("name";"Blountsville";"zc";35031))
$b:=$c.every($f;Is real) //$b=false
.extract()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
$1.result (boolean): true se $1.value < $1.value2, false do contrário
Parameter | Type | Descrição | |
---|---|---|---|
propertyPath | Texto | -> | Rota de propriedade de objeto cujos valores serão extraídos para nova coleção |
targetpath | Texto | -> | Rota de propriedade alvo ou nome propriedade |
option | Integer | -> | ck keep null : inclui propriedades null na coleção retornada (ignorado como padrão). Parâmetro ignorado se for passado targetPath. |
Resultado | Coleção | <- | Nova collection contendo valores extraídos |
Descrição
propertyPath não for encontrada na collection.
This function does not modify the original collection.
Os conteúdos da coleção retornada depende do parâmetro targetPath:
Se o parâmetro targetPath for omitido,
.extract()
preenche a nova coleção com os valores propertyPath da coleção original.Como padrão, elementos para os quais propertyPath for null ou undefined são ignorados na coleção resultante. Pode passar a constante
ck keep null
no parâmetro option para incluir esses valores como elementos null na coleção retornada.
- Se um ou mais parâmetros targetPath forem passados,,
.extract()
preenche a nova coelção com as propriedades propertyPath e cada elemento da nova coleção é um objeto com as propriedades targetPath preenchidas com as propriedades correspondentes propertyPath. Valores null são mantidos (o parâmetro option é ignorado com essa sintaxe).
Exemplo 1
var $c : Collection
$c:=New collection
$c.push(New object("name";"Cleveland"))
$c.push(New object("zip";5321))
$c.push(New object("name";"Blountsville"))
$c.push(42)
$c2:=$c.extract("name") // $c2=[Cleveland,Blountsville]
$c2:=$c.extract("name";ck keep null) //$c2=[Cleveland,null,Blountsville,null]
Exemplo 2
var $c : Collection
$c:=New collection
$c.push(New object("zc";35060))
$c.push(New object("name";Null;"zc";35049))
$c.push(New object("name";"Cleveland";"zc";35049))
$c.push(New object("name";"Blountsville";"zc";35031))
$c.push(New object("name";"Adger";"zc";35006))
$c.push(New object("name";"Clanton";"zc";35046))
$c.push(New object("name";"Clanton";"zc";35045))
$c2:=$c.extract("name";"City") //$c2=[{City:null},{City:Cleveland},{City:Blountsville},{City:Adger},{City:Clanton},{City:Clanton}]
$c2:=$c.extract("name";"City";"zc";"Zip") //$c2=[{Zip:35060},{City:null,Zip:35049},{City:Cleveland,Zip:35049},{City:Blountsville,Zip:35031},{City:Adger,Zip:35006},{City:Clanton,Zip:35046},{City:Clanton,Zip:35045}]
.fill()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.fill( value : any ) : Collection
.fill( value : any ; startFrom : Integer { ; end : Integer } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
value | number, Text, Collection, Object, Date, Boolean | -> | Valores preenchido |
startFrom | Integer | -> | Início do índice (incluído) |
end | Integer | -> | Final do índice (não incluído) |
Resultado | collection | <- | Coleção original com valores preenchidos |
Descrição
Se index < 0, será recalculado como index:=index+length (é considerado como o offset do final da coleção).
This function modifies the original collection.
- Se o parâmetro startFrom for omitido, value é estabelecido para todos os elementos coleção (startFrom=0).
- Se o parâmetro startFrom for passado e o parâmetroend for omitido, value é estabelecido para elementos de coleção começando com startFrom até o elemento final da coleção (end=length).
- Se tanto startFrom quanto end forem passados, value é estabelecido para elementos coleção começando em startFrom ao elemento end.
Em caso de inconsistências, as regras abaixos são seguidas:
- Se index < 0, será recalculado como startFrom:=startFrom+length (é considerado como o offset do final da coleção). Se o valor calculado for negativo, startFrom toma o valor 0.
- Se end < 0 , é recalculado como sendo end:=end+length.
- Se end < startFrom (valores passados ou calculados), o método não faz nada.
Exemplo
var $c : Collection
$c:=New collection(1;2;3;"Lemon";Null;"";4;5)
$c.fill("2") // $c:=[2,2,2,2,2,2,2,2]
$c.fill("Hello";5) // $c=[2,2,2,2,2,Hello,Hello,Hello]
$c.fill(0;1;5) // $c=[2,0,0,0,0,Hello,Hello,Hello]
$c.fill("world";1;-5) //-5+8=3 -> $c=[2,"world","world",0,0,Hello,Hello,Hello]
.filter()
Histórico
Versão | Mudanças |
---|---|
v19 R6 | Support of formula |
v16 R6 | Adicionado |
.filter( formula : 4D. Function { ; ...param : any } ) : Collection
.filter( methodName : Text { ; ...param : any } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
formula | 4D. Function | -> | Formula object |
methodName | Texto | -> | Name of a method |
param | any | -> | Parameter(s) to pass to formula or methodName |
Resultado | Coleção | <- | Nova coleção contendo elementos filtrados (cópia superficial) |
Descrição
A função .query()
devolve todos os elementos de uma coleção de objetos que coincidem com as condiciones de pesquisa definidas por queryString e (opcionalmente) value ou querySettings. Na coleção original é uma coleção partilhada, a coleção retornada também é uma coleção partilhada.
This function does not modify the original collection.
You designate the callback to be executed to filter collection elements using either:
- formula (recommended syntax), a Formula object that can encapsulate any executable expressions, including functions and project methods;
- or methodName, the name of a project method (text).
The callback is called with the parameter(s) passed in param (optional). The callback is called with the parameter(s) passed in param (optional). It receives an Object
in first parameter ($1).
The callback receives the following parameters:
- in $1.value: element value to be evaluated
- $2: param
- $N: paramN...
It can set the following parameter(s):
- (mandatory if you used a method) $1.result (Boolean): true if the element value matches the filter condition and must be kept, false otherwise.
- $1.stop (Booleano, opcional): true para parar o método callback. The returned value is the last calculated.
Exemplo 1
Se quiser obter a coleção de elementos textos cujo tamanho for menor que 6:
var $col;$colNew : Collection
$col:=New collection("hello";"world";"red horse";66;"tim";"san jose";"miami")
$colNew:=$col.filter(Formula((Value type($1.value)=Is text) && (Length($1.value)<$2)); 6)
//$colNew=["hello","world","tim","miami"]
Exemplo 2
Se quiser filtrar elementos de acordo com seu tipo de valor:
var $c;$c2;$c3 : Collection
var $f : 4D. Function
$f:=Formula(OB Get type($1;"value")=$2)
$c:=New collection(5;3;1;4;6;2)
$c.push(New object("name";"Cleveland";"zc";35049))
$c.push(New object("name";"Blountsville";"zc";35031))
$c2:=$c.filter($f;Is real) // $c2=[5,3,1,4,6,2]
$c3:=$c.filter($f;Is object)
// $c3=[{name:Cleveland,zc:35049},{name:Blountsville,zc:35031}]
.find()
Histórico
Versão | Mudanças |
---|---|
v19 R6 | Support of formula |
v16 R6 | Adicionado |
.find( { startFrom : Integer ; } formula : 4D. Function { ; ...param : any } ) : any
.find( { startFrom : Integer ; } methodName : Text { ; ...param : any } ) : any
Parameter | Type | Descrição | |
---|---|---|---|
startFrom | Integer | -> | Índice onde inicia a pesquisa |
formula | 4D. Function | -> | Formula object |
methodName | Texto | -> | Name of a method |
param | any | -> | Parameter(s) to pass to formula or methodName |
Resultado | any | <- | Primeiro valor encontrado ou Undefined se não encontrado |
Descrição
The .find()
function returns the first value in the collection for which formula or methodName result, applied on each element, returns true.
This function does not modify the original collection.
You designate the callback to be executed to evaluate collection elements using either:
- formula (recommended syntax), a Formula object that can encapsulate any executable expressions, including functions and project methods;
- or methodName, the name of a project method (text).
The callback is called with the parameter(s) passed in param (optional). The callback is called with the parameter(s) passed in param (optional). It receives an Object
in first parameter ($1).
The callback receives the following parameters:
- in $1.value: element value to be evaluated
- $2: param
- $N: paramN...
It can set the following parameter(s):
- (mandatory if you used a method) $1.result (Boolean): true if the element value matches the search condition, false otherwise.
- $1.stop (Booleano, opcional): true para parar o método callback. The returned value is the last calculated.
Como padrão, .findIndex()
testa a coleção completa. Opcionalmente pode passar em startFrom o índice do elemento a partir do qual vai começar a pesquisa.
- If startFrom >= the collection's length, -1 is returned, which means the collection is not searched.
- If startFrom < 0, it is considered as the offset from the end of the collection (startFrom:=startFrom+length). Note: Even if startFrom is negative, the collection is still searched from left to right.
- If startFrom = 0, the whole collection is searched (default).
Exemplo 1
You want to get the first text element with a length smaller than 5:
var $col : Collection
$col:=New collection("hello";"world";4;"red horse";"tim";"san jose")
$value:=$col.find(Formula((Value type($1.value)=Is text) && (Length($1.value)<$2)); 5) //$value="tim"
Exemplo 2
Se quiser encontrar o nome da cidade dentro da coleção:
var $c : Collection
var $c2 : Object
$c:=New collection
$c.push(New object("name"; "Cleveland"; "zc"; 35049))
$c.push(New object("name"; "Blountsville"; "zc"; 35031))
$c.push(New object("name"; "Adger"; "zc"; 35006))
$c.push(New object("name"; "Clanton"; "zc"; 35046))
$c.push(New object("name"; "Clanton"; "zc"; 35045))
$c2:=$c.find(Formula($1.value.name=$2); "Clanton") //$c2={name:Clanton,zc:35046}
.findIndex()
Histórico
Versão | Mudanças |
---|---|
v19 R6 | Support of formula |
v16 R6 | Adicionado |
.findIndex( { startFrom : Integer ; } formula : 4D. Function { ; ...param : any } ) : Integer
.findIndex( { startFrom : Integer ; } methodName : Text { ; ...param : any } ) : Integer
Parameter | Type | Descrição | |
---|---|---|---|
startFrom | Integer | -> | Índice onde inicia a pesquisa |
formula | 4D. Function | -> | Formula object |
methodName | Texto | -> | Name of a method |
param | any | -> | Parameter(s) to pass to formula or methodName |
Resultado | Integer | <- | Indice do primeiro valor encontrado ou -1 se não encontrado |
Descrição
The .findIndex()
function returns the index, in the collection, of the first value for which formula or methodName, applied on each element, returns true.
This function does not modify the original collection.
You designate the callback to be executed to evaluate collection elements using either:
- formula (recommended syntax), a Formula object that can encapsulate any executable expressions, including functions and project methods;
- methodName, the name of a project method (text).
The callback is called with the parameter(s) passed in param (optional). The callback is called with the parameter(s) passed in param (optional). It receives an Object
in first parameter ($1).
The callback receives the following parameters:
- in $1.value: element value to be evaluated
- $2: param
- $N: paramN...
It can set the following parameter(s):
- (mandatory if you used a method) $1.result (Boolean): true if the element value matches the search condition, false otherwise.
- $1.stop (Booleano, opcional): true para parar o método callback. The returned value is the last calculated.
Como padrão, .every()
testa a coleção completa. Opcionalmente pode passar em startFrom o índice do elemento a partir do qual vai começar a pesquisa.
- If startFrom >= the collection's length, -1 is returned, which means the collection is not searched.
- If startFrom < 0, it is considered as the offset from the end of the collection (startFrom:=startFrom+length). Note: Even if startFrom is negative, the collection is still searched from left to right.
- If startFrom = 0, the whole collection is searched (default).
Exemplo
Se quiser encontrar a posição do primeiro nome de cidade dentro da coleção:
var $c : Collection
var $val2;$val3 : Integer
$c:=New collection
$c.push(New object("name";"Cleveland";"zc";35049))
$c.push(New object("name";"Blountsville";"zc";35031))
$c.push(New object("name";"Adger";"zc";35006))
$c.push(New object("name";"Clanton";"zc";35046))
$c.push(New object("name";"Clanton";"zc";35045))
$val2:=$c.findIndex(Formula($1.value.name=$2);"Clanton") // $val2=3
$val3:=$c.findIndex($val2+1;Formula($1.value.name=$2);"Clanton") //$val3=4
.indexOf()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.indexOf( toSearch : expression { ; startFrom : Integer } ) : Integer
Parameter | Type | Descrição | |
---|---|---|---|
toSearch | expressão | -> | Expressão a pesquisar na coleção |
startFrom | Integer | -> | Índice onde inicia a pesquisa |
Resultado | Integer | <- | Índice da primeira ocorrência de toSearch na coleção, -1 se não encontrado |
Descrição
Se startFrom = 0, a coleção inteira é pesquisada (padrão).
This function does not modify the original collection.
Em toSearch, passe a expressão para encontrar na coleção. Pode passar:
- a scalar value (text, number, boolean, date),
- o valor null,
- an object or a collection reference.
toSearch deve corresponder exatamente com o elemento a encontrar (as mesmas regras que para o operador de igualdade do tipo dados é aplicado).
Opcionalmente pode passar o índice da coleção para a qual iniciar a pesquisa emstartFrom.
- If startFrom >= the collection's length, -1 is returned, which means the collection is not searched.
- If startFrom < 0, it is considered as the offset from the end of the collection (startFrom:=startFrom+length). Note: Even if startFrom is negative, the collection is still searched from left to right.
- If startFrom = 0, the whole collection is searched (default).
Exemplo
var $col : Collection
var $i : Integer
$col:=New collection(1;2;"Henry";5;3;"Albert";6;4;"Alan";5)
$i:=$col.indexOf(3) //$i=4
$i:=$col.indexOf(5;5) //$i=9
$i:=$col.indexOf("al@") //$i=5
$i:=$col.indexOf("Hello") //$i=-1
.indices()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.indices( queryString : Text { ; ...value : any } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
queryString | Texto | -> | Critérios de pesquisa |
value | any | -> | Valores a comparar quando usar placeholders (valores temporários) |
Resultado | Coleção | <- | Índices elemento correspondendo a queryString na coleção |
Descrição
A função .indices()
trabalha exatamente da mesma forma que a função .query()
mas retorna indices na coleção original, de elementos coleção objeto que correspondem às queryString condições de pesquisa, e não os elementos em si mesmo. Indices são retornados em ordem ascendente.
This function does not modify the original collection.
O parâmetro queryString usa a sintaxe abaixo:
valor de comparação propertyPath {valor de comparação logicalOperator propertyPath}
Para uma descrição detalhada dos parâmetros queryString e value, veja a função dataClass.query()
.
Exemplo
var $c; $icol : Collection
$c:=New collection
$c.push(New object("name";"Cleveland";"zc";35049))
$c.push(New object("name";"Blountsville";"zc";35031))
$c.push(New object("name";"Adger";"zc";35006))
$c.push(New object("name";"Clanton";"zc";35046))
$c.push(New object("name";"Clanton";"zc";35045))
$icol:=$c.indices("name = :1";"Cleveland") // $icol=[0]
$icol:=$c.indices("zc > 35040") // $icol=[0,3,4]
.insert()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.insert( index : Integer ; element : any ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
index | Integer | -> | Onde inserir os elementos |
element | any | -> | Elemento a inserir na coleção |
Resultado | Coleção | <- | Collection original contendo elementos inseridos |
Descrição
A função .insert()
insere element na posição especificada index na instância da coleção e retorna a coleção editada.
This function modifies the original collection.
In index, passe a posição onde quiser que o elemento seja inserido na coleção.
Warning: Keep in mind that collection elements are numbered from 0.
- Se index > o tamanho da coleção, o índice de início é estabelecido como o tamanho da coleção.
- Se index < 0, será recalculado como index:=index+length (é considerado como o offset do final da coleção).
- Se o valor calculado for negativo, index será estabelecido como 0.
Qualquer tipo de elemento aceito por uma coleção pode ser inserido, mesmo outra coleção.
Exemplo
var $col : Collection
$col:=New collection("a";"b";"c";"d") //$col=["a","b","c","d"]
$col.insert(2;"X") //$col=["a","b","X","c","d"]
$col.insert(-2;"Y") //$col=["a","b","X","Y","c","d"]
$col.insert(-10;"Hi") //$col=["Hi","a","b","X","Y","c","d"]
.join()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.join( delimiter : Text { ; option : Integer } ) : Text
Parameter | Type | Descrição | |
---|---|---|---|
delimiter | Texto | -> | Separador a usar entre os elementos |
option | Integer | -> | ck ignore null or empty : ignora strings vazias ou nulls no resultado |
Resultado | Texto | <- | String contendo todos os elementos da coleção, separados por um delimitador |
Descrição
a função .join()
converte todos os elementos da coleção para strings e concatena-os usando a string especificada delimiter como um separador. A função retorna a string resultado.
This function does not modify the original collection.
Como padrão, elementos null ou vazios da coleção são retornados na string resultante. Passe a constante ck ignore null or empty
na opção option parâmetro se quiser removê-las da string resultado.
Exemplo
var $c : Collection
var $t1;$t2 : Text
$c:=New collection(1;2;3;"Paris";Null;"";4;5)
$t1:=$c.join("|") //1|2|3|Paris|null||4|5
$t2:=$c.join("|";ck ignore null or empty) //1|2|3|Paris|4|5
.lastIndexOf()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.lastIndexOf( toSearch : expression { ; startFrom : Integer } ) : Integer
Parameter | Type | Descrição | |
---|---|---|---|
toSearch | expressão | -> | O elemento que é pesquisado dentro da coleção |
startFrom | Integer | -> | Índice onde inicia a pesquisa |
Resultado | Integer | <- | Índice da última ocorrência de toSearch na coleção, -1 se não encontrado |
Descrição
A função.lastIndexOf()
pesquisa a expressão toSearch entre os elementos da coleção e retorna o índice da primeira ocorrência , ou -1 se não for encontrado
This function does not modify the original collection.
Em toSearch, passe a expressão para encontrar na coleção. Pode passar:
- a scalar value (text, number, boolean, date),
- o valor null,
- an object or a collection reference.
Opcionalmente pode passar o índice da coleção para a qual iniciar a pesquisa reversa em startFrom.
Se startFrom = 0, a coleção inteira é pesquisada (padrão).
- Se startFrom >= o tamanho da coleção menos um (coll.length-1), a coleção inteira é pesquisada (padrão).
- Se index < 0, será recalculado como startFrom:=startFrom+length (é considerado como o offset do final da coleção). Se o valor calculado for negativo, -1 é retornado (a coleção não é pesquisada). Nota: Mesmo se startFrom for negativo, a coleção ainda é pesquisada da direita para esquerda.
- Se startFrom = 0, é retornado -1, o que significa que a coleção não é pesquisada.
Exemplo
var $col : Collection
var $pos1;$pos2;$pos3;$pos4;$pos5 : Integer
$col:=Split string("a,b,c,d,e,f,g,h,i,j,e,k,e";",") //$col.length=13
$pos1:=$col.lastIndexOf("e") //returns 12
$pos2:=$col.lastIndexOf("e";6) //returns 4
$pos3:=$col.lastIndexOf("e";15) //returns 12
$pos4:=$col.lastIndexOf("e";-2) //returns 10
$pos5:=$col.lastIndexOf("x") //returns -1
.length
Histórico
Versão | Mudanças |
---|---|
v16 R5 | Adicionado |
.length : Integer
Descrição
A propriedade .length
retorna o número de elementos na coleção.
A propriedade .length
é iniciada quando a coleção for criada. Adicionar ou remover elementos atualiza o tamanho, se necessário. Essa propriedade é read-only /apenas leitura (não pode usá-la para estabelecer o tamanho da coleção).
Exemplo
var $col : Collection //$col.length inicializa em 0
$col:=New collection("one";"two";"three") //$col.length atualizado a 3
$col[4]:="five" //$col.length atualizado a 5
$vSize:=$col.remove(0;3).length //$vSize=2
.map()
Histórico
Versão | Mudanças |
---|---|
v19 R6 | Support of formula |
v16 R6 | Adicionado |
.map( formula : 4D. Function { ; ...param : any } ) : Collection
.map( methodName : Text { ; ...param : any } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
formula | 4D. Function | -> | Formula object |
methodName | Texto | -> | Name of a method |
param | any | -> | Parameter(s) to pass to formula or methodName |
Resultado | Coleção | <- | Collection de valores transformados |
Descrição
The .map()
function creates a new collection based upon the result of the call of the formula 4D function or methodName method on each element of the original collection. Optionally, you can pass parameters to formula or methodName using the param parameter(s). .map()
sempre retorna uma coleção com o mesmo tamanho que a coleção original.
This function does not modify the original collection.
You designate the callback to be executed to evaluate collection elements using either:
- formula (recommended syntax), a Formula object that can encapsulate any executable expressions, including functions and project methods;
- or methodName, the name of a project method (text).
The callback is called with the parameter(s) passed in param (optional). The callback is called with the parameter(s) passed in param (optional). It receives an Object
in first parameter ($1).
The callback receives the following parameters:
- in $1.value: element value to be evaluated
- $2: param
- $N: paramN...
It can set the following parameter(s):
- (mandatory if you used a method) $1.result (any type): new transformed value to add to the resulting collection
- $1.stop (Booleano, opcional): true para parar o método callback. The returned value is the last calculated.
Exemplo
var $c; $c2 : Collection
$c:=New collection(1; 4; 9; 10; 20)
$c2:=$c.map(Formula(Round(($1.value/$2)*100; 2)); $c.sum())
//$c2=[2.27,9.09,20.45,22.73,45.45]
.max()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.max( { propertyPath : Text } ) : any
Parameter | Type | Descrição | |
---|---|---|---|
propertyPath | Texto | -> | Rota de propriedade objeto a ser usado para avaliação |
Resultado | Boolean, Text, Number, Collection, Object, Date | <- | Valor máximo na coleção |
Descrição
Se a coleção conter diferentes tipos de valores, a função .max()
devolverá o valor máximo dentro do último tipo de elemento na orde, da lista de tipos (ver a descrição de .sort()
).
This function does not modify the original collection.
Se a coleção conter objetos, pode passar o parâmetro propertyPath para indicar a propriedade objeto cujos valores máximos você quer obter.
Se a coleção estiver vazia, .max()
devolve Undefined.
Se end < 0 , é recalculado como sendo end:=end+length.
Exemplo
var $col : Collection
$col:=New collection(200;150;55)
$col.push(New object("name";"Smith";"salary";10000))
$col.push(New object("name";"Wesson";"salary";50000))
$col.push(New object("name";"Alabama";"salary";10500))
$max:=$col.max() //{name:Alabama,salary:10500}
$maxSal:=$col.max("salary") //50000
$maxName:=$col.max("name") //"Wesson"
.min()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.min( { propertyPath : Text } ) : any
Parameter | Type | Descrição | |
---|---|---|---|
propertyPath | Texto | -> | Rota de propriedade objeto a ser usado para avaliação |
Resultado | Boolean, Text, Number, Collection, Object, Date | <- | Valor mínimo na coleção |
Descrição
A função .min()
retorna o elemento com o menor valor na coleção (o primeiro elemento da coleção como seria ordenado de forma ascendente usando a função .sort()
).
This function does not modify the original collection.
Se a coleção conter diferentes tipos de valores, a função .min()
devolverá o valor mínimo dentro do primeiro tipo de elemento na ordem da lista de tipos (ver a descrição de .sort()
).
Se a coleção conter objetos, pode passar o parâmetro propertyPath para indicar a propriedade objeto cujos valores mínimos você quer obter.
Se a coleção estiver vazia, .min()
devolve Undefined.
Exemplo
var $col : Collection
$col:=New collection(200;150;55)
$col.push(New object("name";"Smith";"salary";10000))
$col.push(New object("name";"Wesson";"salary";50000))
$col.push(New object("name";"Alabama";"salary";10500))
$min:=$col.min() //55
$minSal:=$col.min("salary") //10000
$minName:=$col.min("name") //"Alabama"
.orderBy()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.orderBy( ) : Collection
.orderBy( pathStrings : Text ) : Collection
.orderBy( pathObjects : Collection ) : Collection
.orderBy( ascOrDesc : Integer ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
pathStrings | Texto | -> | Property path(s) on which to order the collection |
pathObjects | Coleção | -> | Collection of criteria objects |
ascOrDesc | Integer | -> | ck ascending or ck descending (scalar values) |
Resultado | Coleção | <- | Ordered copy of the collection (shallow copy) |
Descrição
A função .orderBy()
devolve uma nova coleção que contém todos os elementos da coleção na ordem especificado.
Esta função devolve uma cópia superficial, o que significa que os objetos ou coleções de ambas coleções compartem a mesma referência. Na coleção original é uma coleção partilhada, a coleção retornada também é uma coleção partilhada.
This function does not modify the original collection.
Se não passar nenhum parâmetro, a função ordena os valores escalares da coleção em ordem ascendente (outros tipos de elementos, como objetos ou coleções, se devolvem desordenados). Pode modificar esta ordem automático passando as constantes ck ascending
ou ck descending
no parâmetro ascOrDesc (ver abaixo).
Também pode passar um parâmetro de critérios para definir como devem ordenar-se os elementos da coleção. Três sintaxes são compatíveis com esse parâmetro:
pathStrings : Text (fórmula). Syntax:
propertyPath1 {desc or asc}, propertyPath2 {desc or asc},...
(default order: asc). pathStrings contém uma fórmula composta de 1 a x rotas de propriedades e (opcionalmente) ordens de classificação, separados por vírgulas. A ordem na qual as propriedades são passadas determina a prioridade de ordenação dos elementos da coleção Como padrão as propriedades são ordenadas de forma ascendente. Pode definir a ordem de clasificação de uma propriedade na string de critérios, separado da rota da propriedade por um só espaço: passe "asc" para ordenar em ordem ascendente ou "desc" em ordem descendente.pathObjects : Collection. Pode adicionar tantos objetos na coleção pathObjects como seja necessário. Como padrão, as propriedades se classificam em ordem ascendente ("descending" é false). Cada elemento da coleção contém um objeto estruturado da seguinte maneira:
{
"propertyPath": string,
"descending": boolean
}
ascOrDesc: Integer. Se passar uma das seguintes constantes do tema Objects and collections:
Constante Type Value Comentário ck ascending Inteiro longo 0 Os elementos são ordenados de forma ascendente (por padrão) ck descending Inteiro longo 1 Os elementos são ordenados de forma descendente Essa sintaxe ordena apenas os valores escalares da coleção (outros tipos de elementos como objetos ou coleções são retornados sem ordenar).
Se a coleção conter elementos de tipos diferentes, são primeiro agrupados por tipo e ordenados depois. Se attributePath levar a uma propriedade de objeto que conter valores de diferentes tipos, primeiro se agrupam por tipo e se ordenam depois.
- null
- booleans
- strings
- numbers
- objetos
- collections
- datas
Exemplo 1
Ordenar uma coleção de números em ordem ascendente e descendente:
var $c; $c2; $3 : Collection
$c:=New collection
For($vCounter;1;10)
$c.push(Random)
End for
$c2:=$c.orderBy(ck ascending)
$c3:=$c.orderBy(ck descending)
Exemplo 2
Ordenar uma coleção de objetos a partir de uma fórmula de texto com nomes de propriedades:
var $c; $c2 : Collection
$c:=New collection
For($vCounter;1;10)
$c.push(New object("id";$vCounter;"value";Random))
End for
$c2:=$c.orderBy("value desc")
$c2:=$c.orderBy("value desc, id")
$c2:=$c.orderBy("value desc, id asc")
Ordenar uma coleção de objetos com uma rota de propriedades:
var $c; $c2 : Collection
$c:=New collection
$c.push(New object("name";"Cleveland";"phones";New object("p1";"01";"p2";"02")))
$c.push(New object("name";"Blountsville";"phones";New object("p1";"00";"p2";"03")))
$c2:=$c.orderBy("phones.p1 asc")
Exemplo 3
Ordenar uma coleção de objetos utilizando uma coleção de objetos critério:
var $crit; $c; $c2 : COllection
$crit:=New collection
$c:=New collection
For($vCounter;1;10)
$c.push(New object("id";$vCounter;"value";Random))
End for
$crit.push(New object("propertyPath";"value";"descending";True))
$crit.push(New object("propertyPath";"id";"descending";False))
$c2:=$c.orderBy($crit)
Ordenar com uma rota de propriedade:
var $crit; $c; $c2 : Collection
$c:=New collection
$c.push(New object("name";"Cleveland";"phones";New object("p1";"01";"p2";"02")))
$c.push(New object("name";"Blountsville";"phones";New object("p1";"00";"p2";"03")))
$crit:=New collection(New object("propertyPath";"phones.p2";"descending";True))
$c2:=$c.orderBy($crit)
.orderByMethod()
Histórico
Versão | Mudanças |
---|---|
v19 R6 | Support of formula |
v16 R6 | Adicionado |
.orderByMethod( formula : 4D. Function { ; ...extraParam : expression } ) : Collection
.orderByMethod( methodName : Text { ; ...extraParam : expression } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
formula | 4D. Function | -> | Formula object |
methodName | Texto | -> | Name of a method |
extraParam | any | -> | Parameter(s) to pass |
Resultado | Coleção | <- | Cópia ordenada da coleção (cópia superficial) |
Descrição
The .orderByMethod()
function returns a new collection containing all elements of the collection in the order defined through the formula 4D function or methodName method.
Esta função devolve uma cópia superficial, o que significa que os objetos ou coleções de ambas coleções compartem a mesma referência. Na coleção original é uma coleção partilhada, a coleção retornada também é uma coleção partilhada.
This function does not modify the original collection.
You designate the callback to be executed to evaluate collection elements using either:
- formula (recommended syntax), a Formula object that can encapsulate any executable expressions, including functions and project methods;
- or methodName, the name of a project method (text).
In the callback, pass some code that compares two values and returns true if the first value is lower than the second value. You can provide extraParam parameters to the callback if necessary.
The callback receives the following parameters:
- $1 (objeto), onde:
- em $1.value (qualquer tipo): primeiro elemento a ser comparado
- em $1.value2 (qualquer tipo): segundo elemento a ser comparado
- $2...$N (qualquer tipo): parâmetros adicionais
If you used a method, it must set the following parameter:
- $1.result (boolean): true se $1.value < $1.value2, false do contrário
Exemplo 1
Se quiser ordenar a coleção de strings em ordem numérica ao invés de ordem alfabética:
var $c; $c2; $c3 : Collection
$c:=New collection
$c.push("33";"4";"1111";"222")
$c2:=$c.orderBy() //$c2=["1111","222","33","4"], alphabetical order
$c3:=$c.orderByMethod(Formula(Num($1.value)<Num($1.value2))) // $c3=["4","33","222","1111"]
Exemplo 2
Se quiser ordenar a coleção de strings de acordo com seu tamanho:
var $fruits; $c2 : Collection
$fruits:=New collection("Orange";"Apple";"Grape";"pear";"Banana";"fig";"Blackberry";"Passion fruit")
$c2:=$fruits.orderByMethod(Formula(Length(String($1.value))>Length(String($1.value2))))
//$c2=[Passion fruit,Blackberry,Orange,Banana,Apple,Grape,pear,fig]
Exemplo 3
Se quiser ordenar a coleção por código de caractere ou alfabeticamente:
var $strings1; $strings2 : Collection
$strings1:=New collection("Alpha";"Charlie";"alpha";"bravo";"Bravo";"charlie")
//using the character code:
$strings2:=$strings1.orderByMethod(Function(sortCollection);sk character codes)
// result : ["Alpha","Bravo","Charlie","alpha","bravo","charlie"]
//using the language:
$strings2:=$string1s.orderByMethod(Function(sortCollection);sk strict)
// result : ["alpha","Alpha","bravo","Bravo","charlie","Charlie"]
Aqui está o método sortCollection:
var $1 : Object
var $2: Integer // sort option
$1.result:=(Compare strings($1.value;$1.value2;$2)<0)
.pop()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.pop() : any
Parameter | Type | Descrição | |
---|---|---|---|
Resultado | any | <- | Último elemento da coleção |
Descrição
A função .pop()
elimina o último elemento da coleção e o devolve como resultado da função.
This function modifies the original collection.
Quando for aplicado a uma coleção vazia, .pop()
devolve undefined.
Exemplo
.pop()
, utilizado junto com .push()
, pode ser utilizado para implementar uma funcionalidade primeira entrada, última saída de tratamento de dados empilhados:
var $stack : Collection
$stack:=New collection //$stack=[]
$stack.push(1;2) //$stack=[1,2]
$stack.pop() //$stack=[1] Returns 2
$stack.push(New collection(4;5)) //$stack=[[1,[4,5]]
$stack.pop() //$stack=[1] Returns [4,5]
$stack.pop() //$stack=[] Returns 1
.push()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.push( element : any { ;...elementN } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
element | Mixed | -> | Elementos a adicionar à coleção |
Resultado | Coleção | <- | Collection original contendo elementos inseridos |
Descrição
A função .push()
adiciona um ou mais elementos ao final da instância da coleção e devolve a coleção editada.
This function modifies the original collection.
Exemplo 1
var $col : Collection
$col:=New collection(1;2) //$col=[1,2]
$col.push(3) //$col=[1,2,3]
$col.push(6;New object("firstname";"John";"lastname";"Smith"))
//$col=[1,2,3,6,{firstname:John,lastname:Smith}
Exemplo 2
Se quiser ordenar a coleção resultante:
var $col; $sortedCol : Collection
$col:=New collection(5;3;9) //$col=[5,3,9]
$sortedCol:=$col.push(7;50).sort()
//$col=[5,3,9,7,50]
//$sortedCol=[3,5,7,9,50]
.query()
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Assistência de querySettings |
v16 R6 | Adicionado |
.query( queryString : Text ; ...value : any ) : Collection
.query( queryString : Text ; querySettings : Object ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
queryString | Texto | -> | Critérios de pesquisa |
value | Mixed | -> | Valores a comparar quando usar placeholders (valores temporários) |
querySettings | Objeto | -> | Opções de pesquisa: parâmetros, atributos |
Resultado | Coleção | <- | Elementos que correspondem com queryString na coleção |
Descrição
Esta função devolve uma cópia superficial, o que significa que os objetos ou coleções de ambas coleções compartem a mesma referência. Na coleção original é uma coleção partilhada, a coleção retornada também é uma coleção partilhada.
This function does not modify the original collection.
O parâmetro queryString usa a sintaxe abaixo:
valor de comparação propertyPath {valor de comparação logicalOperator propertyPath}
Para obter informação detalhada sobre como construir uma consulta utilizando os parâmetros queryString, value e querySettings, consulte a descrição da função dataClass.query()
.
As fórmulas não tem compatibilidade com a função
collection.query()
, nem com o parâmetro queryString nem como parâmetro do objeto fórmula.
Exemplo 1
var $c; $c2; $c3 : Collection
$c:=New collection
$c.push(New object("name";"Cleveland";"zc";35049))
$c.push(New object("name";"Blountsville";"zc";35031))
$c.push(New object("name";"Adger";"zc";35006))
$c.push(New object("name";"Clanton";"zc";35046))
$c.push(New object("name";"Clanton";"zc";35045))
$c2:=$c.query("name = :1";"Cleveland") //$c2=[{name:Cleveland,zc:35049}]
$c3:=$c.query("zc > 35040") //$c3=[{name:Cleveland,zc:35049},{name:Clanton,zc:35046},{name:Clanton,zc:35045}]
Exemplo 2
var $c : Collection
$c:=New collection
$c.push(New object("name";"Smith";"dateHired";!22-05-2002!;"age";45))
$c.push(New object("name";"Wesson";"dateHired";!30-11-2017!))
$c.push(New object("name";"Winch";"dateHired";!16-05-2018!;"age";36))
$c.push(New object("name";"Sterling";"dateHired";!10-5-1999!;"age";Null))
$c.push(New object("name";"Mark";"dateHired";!01-01-2002!))
Este exemplo devolve as pessoas cujo nome contém "in":
$col:=$c.query("name = :1";"@in@")
//$col=[{name:Winch...},{name:Sterling...}]
Este exemplo devolve as pessoas cujo nome não começa por uma string de uma variável (introduzida pelo usuário, por exemplo):
$col:=$c.query("name # :1";$aString+"@")
//if $astring="W"
//$col=[{name:Smith...},{name:Sterling...},{name:Mark...}]
Este exemplo devolve as pessoas cuja idade não se conhece (propriedade definida como null ou indefinida):
$col:=$c.query("age=null") //não são permitidos placeholders ou marcadores de posição com "null"
//$col=[{name:Wesson...},{name:Sterling...},{name:Mark...}]
Este exemplo devolve as pessoas contratadas há mais de 90 dias:
$col:=$c.query("dateHired < :1";(Current date-90))
//$col=[{name:Smith...},{name:Sterling...},{name:Mark...}] if today is 01/10/2018 se hoje for 01/10/2018
Exemplo 3
Mais exemplos de pesquisas podem ser encontrados na página dataClass.query()
.
.reduce()
Histórico
Versão | Mudanças |
---|---|
v19 R6 | Support of formula |
v16 R6 | Adicionado |
.reduce( formula : 4D. Function { ; initValue : any { ; ...param : expression }} ) : any
.reduce( methodName : Text { ; initValue : any { ; ...param : expression }} ) : any
Parameter | Type | Descrição | |
---|---|---|---|
formula | 4D. Function | -> | Formula object |
methodName | Texto | -> | Name of a method |
initValue | Text, Number, Object, Collection, Date, Boolean | -> | Value to use as the first argument to the first call of formula or methodName |
param | expressão | -> | Parameter(s) to pass |
Resultado | Text, Number, Object, Collection, Date, Boolean | <- | Resultado do valor do acumulador |
Descrição
The .reduce()
function applies the formula or methodName callback against an accumulator and each element in the collection (from left to right) to reduce it to a single value.
This function does not modify the original collection.
You designate the callback to be executed to evaluate collection elements using either:
- formula (recommended syntax), a Formula object that can encapsulate any executable expressions, including functions and project methods;
- or methodName, the name of a project method (text).
The callback takes each collection element and performs any desired operation to accumulate the result into $1.accumulator, which is returned in $1.value.
Pode passar o valor para inicializar o acumulador em initValue. Se omitido, $1.accumulator> começa com Undefined.
The callback receives the following parameters:
- em $1.value: valor elemento a ser processado
- in $2: param
- em $N...: paramN...
The callback sets the following parameter(s):
- $1.accumulator: valor que vai ser modificado pela função e que é inicializado por initValue.
- $1.stop (boolean, opcional): true para parar o callback do método. The returned value is the last calculated.
Exemplo 1
var $c : Collection
$c:=New collection(5;3;5;1;3;4;4;6;2;2)
$r:=$c.reduce(Formula($1.accumulator:=$1.accumulator*$1.value); 1) //returns 86400
Exemplo 2
Este exemplo permite reduzir vários elementos da coleção a um só:
var $c;$r : Collection
$c:=New collection
$c.push(New collection(0;1))
$c.push(New collection(2;3))
$c.push(New collection(4;5))
$c.push(New collection(6;7))
$r:=$c.reduce(Formula(Flatten)) //$r=[0,1,2,3,4,5,6,7]
Com o método Flatten:
If($1.accumulator=Null)
$1.accumulator:=New collection
End if
$1.accumulator.combine($1.value)
.remove()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.remove( index : Integer { ; howMany : Integer } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
index | Integer | -> | Elemento no qual que se inicia a eliminação |
howMany | Integer | -> | Número de elementos a eliminar, ou 1 elemento se omitir |
Resultado | Coleção | <- | Colección original sem elementos eliminados |
Descrição
The .remove()
function removes one or more element(s) from the specified index position in the collection and returns the edited collection.
This function modifies the original collection.
In index, pass the position where you want the element to be removed from the collection.
Warning: Keep in mind that collection elements are numbered from 0. If startFrom < 0, it is considered as the offset from the end of the collection (startFrom:=startFrom+length).
- If index < 0, it is recalculated as index:=index+length (it is considered as the offset from the end of the collection).
- If the calculated value < 0, index is set to 0.
- If the calculated value > the length of the collection, index is set to the length.
In howMany, pass the number of elements to remove from index. If howMany is not specified, then one element is removed.
If you try to remove an element from an empty collection, the method does nothing (no error is generated).
Exemplo
var $col : Collection
$col:=New collection("a";"b";"c";"d";"e";"f";"g";"h")
$col.remove(3) // $col=["a","b","c","e","f","g","h"]
$col.remove(3;2) // $col=["a","b","c","g","h"]
$col.remove(-8;1) // $col=["b","c","g","h"]
$col.remove(-3;1) // $col=["b","g","h"]
.resize()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.resize( size : Integer { ; defaultValue : any } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
size | Integer | -> | New size of the collection |
defaultValue | Number, Text, Object, Collection, Date, Boolean | -> | Default value to fill new elements |
Resultado | Coleção | <- | Resized original collection |
Descrição
The .resize()
function sets the collection length to the specified new size and returns the resized collection.
This function modifies the original collection.
- If size < collection length, exceeding elements are removed from the collection.
- If size > collection length, the collection length is increased to size.
By default, new elements are filled will null values. You can specify the value to fill in added elements using the defaultValue parameter.
Exemplo
var $c : Collection
$c:=New collection
$c.resize(10) // $c=[null,null,null,null,null,null,null,null,null,null]
$c:=New collection
$c.resize(10;0) // $c=[0,0,0,0,0,0,0,0,0,0]
$c:=New collection(1;2;3;4;5)
$c.resize(10;New object("name";"X")) //$c=[1,2,3,4,5,{name:X},{name:X},{name:X},{name:X},{name:X}]
$c:=New collection(1;2;3;4;5)
$c.resize(2) //$c=[1,2]
.reverse()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.reverse( ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
Resultado | Coleção | <- | Inverted copy of the collection |
Descrição
The .sort()
function <!-- REF #collection.sort(). Na coleção original é uma coleção partilhada, a coleção retornada também é uma coleção partilhada.
This function does not modify the original collection.
Exemplo
var $c : Collection
$c:=New collection
$c.push(New object("name";"Smith";"dateHired";!22-05-2002!;"age";45))
$c.push(New object("name";"Wesson";"dateHired";!30-11-2017!))
$c.push(New object("name";"Winch";"dateHired";!16-05-2018!;"age";36))
$c.push(New object("name";"Sterling";"dateHired";!10-5-1999!;"age";Null))
$c.push(New object("name";"Mark";"dateHired";!01-01-2002!))
.shift()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.shift() : any
Parameter | Type | Descrição | |
---|---|---|---|
Resultado | any | <- | First element of collection |
Descrição
The .shift()
function removes the first element of the collection and returns it as the function result.
This function modifies the original collection.
If the collection is empty, this method does nothing.
Exemplo
var $c : Collection
var $val : Variant
$c:=New collection(1;2;4;5;6;7;8)
$val:=$c.shift()
// $val=1
// $c=[2,4,5,6,7,8]
.slice()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.slice( startFrom : Integer { ; end : Integer } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
startFrom | Integer | -> | Início do índice (incluído) |
end | Integer | -> | Final do índice (não incluído) |
Resultado | Coleção | <- | New collection containing sliced elements (shallow copy) |
Descrição
A função .query()
devolve todos os elementos de uma coleção de objetos que coincidem com as condiciones de pesquisa definidas por queryString e (opcionalmente) value ou querySettings. Na coleção original é uma coleção partilhada, a coleção retornada também é uma coleção partilhada.
This function does not modify the original collection.
The returned collection contains the element specified by startFrom and all subsequent elements up to, but not including, the element specified by end. If only the startFrom parameter is specified, the returned collection contains all elements from startFrom to the last element of the original collection.
- Se index < 0, será recalculado como startFrom:=startFrom+length (é considerado como o offset do final da coleção).
- If the calculated value < 0, startFrom is set to 0.
- Se end < 0 , é recalculado como sendo end:=end+length.
- If end < startFrom (passed or calculated values), the method does nothing.
Exemplo
var $c; $nc : Collection
$c:=New collection(1;2;3;4;5)
$nc:=$c.slice(0;3) //$nc=[1,2,3]
$nc:=$c.slice(3) //$nc=[4,5]
$nc:=$c.slice(1;-1) //$nc=[2,3,4]
$nc:=$c.slice(-3;-2) //$nc=[3]
.some()
Histórico
Versão | Mudanças |
---|---|
v19 R6 | Support of formula |
v16 R6 | Adicionado |
.some( { startFrom : Integer ; } formula : 4D. Function { ; ...param : any } ) : Boolean
.some( { startFrom : Integer ; } methodName : Text { ; ...param : any } ) : Boolean
Parameter | Type | Descrição | |
---|---|---|---|
startFrom | Integer | -> | Índice para início do teste em |
formula | 4D. Function | -> | Formula object |
methodName | Texto | -> | Name of a method |
param | Mixed | -> | Parameter(s) to pass |
Resultado | Booleano | <- | True if at least one element successfully passed the test |
Descrição
The .some()
function returns true if at least one element in the collection successfully passed a test implemented in the provided formula or methodName code.
You designate the 4D code (callback) to be executed to evaluate collection elements using either:
- formula (recommended syntax), a Formula object that can encapsulate any executable expressions, including functions and project methods;
- or methodName, the name of a project method (text).
The callback is called with the parameter(s) passed in param (optional). The callback can perform any test, with or without the parameter(s) and must return true for every element fulfilling the test. It receives an Object
in first parameter ($1).
The callback receives the following parameters:
- em $1.value: valor elemento a ser processado
- in $2: param
- em $N...: paramN...
It can set the following parameter(s):
- (mandatory if you used a method) $1.result (boolean): true if the element value evaluation is successful, false otherwise.
- $1.stop (boolean, opcional): true para parar o callback do método. The returned value is the last calculated.
In any case, at the point where .some()
function encounters the first collection element returning true, it stops calling the callback and returns true.
By default, .some()
tests the whole collection. Optionally, you can pass the index of an element from which to start the test in startFrom.
- If startFrom >= the collection's length, False is returned, which means the collection is not tested.
- If startFrom < 0, it is considered as the offset from the end of the collection.
- If startFrom = 0, the whole collection is searched (default).
Exemplo
You want to know if at least one collection value is >0.
var $c : Collection
var $b : Boolean
$c:=New collection
$c.push(-5;-3;-1;-4;-6;-2)
$b:=$c.some(Formula($1.value>0)) // $b=false
$c.push(1)
$b:=$c.some(Formula($1.value>0)) // $b=true
$c:=New collection
$c.push(1;-5;-3;-1;-4;-6;-2)
$b:=$c.some(Formula($1.value>0)) //$b=true
$b:=$c.some(1;Formula($1.value>0)) //$b=false
.sort()
Histórico
Versão | Mudanças |
---|---|
v19 R6 | Support of formula |
v16 R6 | Adicionado |
.sort( formula : 4D. Function { ; ...extraParam : any } ) : Collection
.sort( methodName : Text { ; ...extraParam : any } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
formula | 4D. Function | -> | Formula object |
methodName | Texto | -> | Name of a method |
extraParam | any | -> | Parâmetros para o método |
Resultado | Coleção | <- | Original collection sorted |
Descrição
The .sort()
function sorts the elements of the original collection and also returns the sorted collection .
This function modifies the original collection.
If .sort()
is called with no parameters, only scalar values (number, text, date, booleans) are sorted. Elements are sorted by default in ascending order, according to their type.
If you want to sort the collection elements in some other order or sort any type of element, you must supply in formula (Formula object) or methodName (Text) a comparison callback that compares two values and returns true if the first value is lower than the second value. You can provide additional parameters to the callback if necessary.
The callback receives the following parameters:
- $1 (objeto), onde:
- em $1.value (qualquer tipo): primeiro elemento a ser comparado
- em $1.value2 (qualquer tipo): segundo elemento a ser comparado
- $2...$N (qualquer tipo): parâmetros adicionais
If you used a method, you must set the folllowing parameter:
- $1.result (boolean): true if $1.value < $1.value2, false otherwise.
Se a coleção conter elementos de tipos diferentes, são primeiro agrupados por tipo e ordenados depois. Se attributePath levar a uma propriedade de objeto que conter valores de diferentes tipos, primeiro se agrupam por tipo e se ordenam depois.
- null
- booleans
- strings
- numbers
- objetos
- collections
- datas
Exemplo 1
var $col; $col2 : Collection
$col:=New collection("Tom";5;"Mary";3;"Henry";1;"Jane";4;"Artie";6;"Chip";2)
$col2:=$col.sort() // $col2=["Artie","Chip","Henry","Jane","Mary","Tom",1,2,3,4,5,6]
// $col=["Artie","Chip","Henry","Jane","Mary","Tom",1,2,3,4,5,6]
Exemplo 2
var $col; $col2 : Collection
$col:=New collection(10;20)
$col2:=$col.push(5;3;1;4;6;2).sort() //$col2=[1,2,3,4,5,6,10,20]
Exemplo 3
var $col; $col2; $col3 : Collection
$col:=New collection(33;4;66;1111;222)
$col2:=$col.sort() //numerical sort: [4,33,66,222,1111]
$col3:=$col.sort(Formula(String($1.value)<String($1.value2))) //alphabetical sort: [1111,222,33,4,66]
.sum()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.sum( { propertyPath : Text } ) : Real
Parameter | Type | Descrição | |
---|---|---|---|
propertyPath | Texto | -> | Rota de propriedade objeto a ser usado para cálculos |
Resultado | Real | <- | Sum of collection values |
Descrição
The .sum()
function returns the sum for all values in the collection instance.
Apenas elementos numéricos são considerados para cálculos (outros tipos são ignorados).
Se a coleção contiver objetos, passe o parâmetro propertyPath para indicar a propriedade objeto para levar em consideração.
.sum()
returns 0 if:
- the collection is empty,
- the collection does not contain numerical elements,
- propertyPath is not found in the collection.
Exemplo 1
var $col : Collection
var $vSum : Real
$col:=New collection(10;20;"Monday";True;2)
$vSum:=$col.sum() //32
Exemplo 2
var $col : Collection
var $vSum : Real
$col:=New collection
$col.push(New object("name";"Smith";"salary";10000))
$col.push(New object("name";"Wesson";"salary";50000))
$col.push(New object("name";"Gross";"salary";10500,5))
$vSum:=$col.sum("salary") //$vSum=70500,5
.unshift()
Histórico
Versão | Mudanças |
---|---|
v16 R6 | Adicionado |
.unshift( value : any { ;...valueN : any } ) : Collection
Parameter | Type | Descrição | |
---|---|---|---|
value | Text, Number, Object, Collection, Date | -> | Value(s) to insert at the beginning of the collection |
Resultado | Real | <- | Collection containing added element(s) |
Descrição
The .unshift()
function inserts the given value(s) at the beginning of the collection and returns the modified collection.
This function modifies the original collection.
If several values are passed, they are inserted all at once, which means that they appear in the resulting collection in the same order as in the argument list.
Exemplo
var $c : Collection
$c:=New collection(1;2)
$c.unshift(4) // $c=[4,1,2]
$c.unshift(5) //$c=[5,4,1,2]
$c.unshift(6;7) // $c=[6,7,5,4,1,2]