Collection
La clase Collection gestiona variables de tipo Collection.
Una colección se inicializa con:
New collection {( ...value : any )} : Collection crea una nueva colección vacía o precargada |
New shared collection {( ...value : any )} : Collection crea una nueva colección compartida vacía o precargada |
Ejemplo
var $colVar : Collection //creación de una variable 4D de tipo colección
$colVar:=New collection //inicialización de la colección y asignación a la variable 4D
Resumen
.at( index : Integer ) : any returns the item at position index, allowing for positive and negative integers |
.average( {propertyPath : Text } ) : Real returns the arithmetic mean (average) of defined values in the collection instance |
.clear() : Collection removes all elements from the collection instance and returns an empty collection |
.combine( col2 : Collection {; index : Integer } ) : Collection inserts col2 elements at the end or at the specified index position in the collection instance and returns the edited collection |
.concat( value : any { ;...valueN } ) : Collection returns a new collection containing the elements of the original collection with all elements of the value parameter added to the end |
.copy() : Collection .copy( option : Integer ) : Collection .copy( option : Integer ; groupWithCol : Collection ) : Collection .copy( option : Integer ; groupWithObj : Object ) : Collection returns a deep copy of the collection instance |
.count( { propertyPath : Text } ) : Real returns the number of non-null elements in the collection |
.countValues( value : any {; propertyPath : Text } ) : Real returns the number of times value is found in the collection |
.distinct( {options : Integer} ) : Collection .distinct( propertyPath : Text {; options : Integer } ) : Collection returns a collection containing only distinct (different) values from the original collection |
.equal( collection2 : Collection {; option : Integer } ) : Boolean recursively compares the contents of the collection and collection2 (deep comparison) |
.every( { startFrom : Integer ; } formula : 4D.Function { ;...param : any } ) : Boolean .every( { startFrom : Integer ; } methodName : Text { ;...param : any } ) : Boolean returns true if all elements in the collection successfully passed a test implemented in the provided formula object or methodName method |
.extract( propertyPath : Text { ; option : Integer } ) : Collection .extract( propertyPath : Text ; targetPath : Text { ;...propertyPathOrTargetPathN : Text } ) : Collection creates and returns a new collection containing propertyPath values extracted from the original collection of objects |
.fill( value : any ) : Collection .fill( value : any ; startFrom : Integer { ; end : Integer } ) : Collection fills the collection with the specified value, optionally from startFrom index to end index, and returns the resulting collection |
.filter( formula : 4D.Function { ; ...param : any } ) : Collection .filter( methodName : Text { ; ...param : any } ) : Collection returns a new collection containing all elements of the original collection for which the formula or methodName result is true |
.find( { startFrom : Integer ; } formula : 4D.Function { ; ...param : any } ) : any .find( { startFrom : Integer ; } methodName : Text { ; ...param : any } ) : any returns the first value in the collection for which formula or methodName result, applied on each element, returns true |
.findIndex( { startFrom : Integer ; } formula : 4D.Function { ; ...param : any } ) : Integer .findIndex( { startFrom : Integer ; } methodName : Text { ; ...param : any } ) : Integer returns the index, in the collection, of the first value for which formula or methodName, applied on each element, returns true |
.first() : any returns the first element of the collection |
.flat( { depth : Integer } ) : Collection creates a new collection with all sub-collection elements concatenated into it recursively up to the specified depth |
.flatMap( formula : 4D.Function { ; ...param : any } ) : Collection .flatMap( methodName : Text { ; ...param : any } ) : Collection 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 and flattened by a depth of 1 |
.includes( toSearch : expression { ; startFrom : Integer } ) : Boolean returns True if the toSearch expression is found among collection elements, otherwise False |
.indexOf( toSearch : expression { ; startFrom : Integer } ) : Integer searches the toSearch expression among collection elements and returns the index of the first found occurrence, or -1 if it was not found |
.indices( queryString : Text { ; ...value : any } ) : Collection returns indexes, in the original collection, of object collection elements that match the queryString search conditions |
.insert( index : Integer ; element : any ) : Collection inserts element at the specified index position in the collection instance and returns the edited collection |
.join( delimiter : Text { ; option : Integer } ) : Text converts all elements of the collection to strings and concatenates them using the specified delimiter string as separator |
.last() : any returns the last element of the collection |
.lastIndexOf( toSearch : expression { ; startFrom : Integer } ) : Integer searches the toSearch expression among collection elements and returns the index of the last occurrence |
.length : Integer returns the number of elements in the collection |
.map( formula : 4D.Function { ; ...param : any } ) : Collection .map( methodName : Text { ; ...param : any } ) : Collection 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 |
.max( { propertyPath : Text } ) : any returns the element with the highest value in the collection |
.min( { propertyPath : Text } ) : any returns the element with the smallest value in the collection |
.multiSort() : Collection .multiSort( colsToSort : Collection ) : Collection .multiSort( formula : 4D.Function ; colsToSort : Collection ) : Collection enables you to carry out a multi-level synchronized sort on a set of collections |
.orderBy( ) : Collection .orderBy( pathStrings : Text ) : Collection .orderBy( pathObjects : Collection ) : Collection .orderBy( ascOrDesc : Integer ) : Collection returns a new collection containing all elements of the collection in the specified order |
.orderByMethod( formula : 4D.Function { ; ...extraParam : expression } ) : Collection .orderByMethod( methodName : Text { ; ...extraParam : expression } ) : Collection returns a new collection containing all elements of the collection in the order defined through the formula 4D function or methodName method |
.pop() : any removes the last element from the collection and returns it as the function result |
.push( element : any { ;...elementN } ) : Collection appends one or more element(s) to the end of the collection instance and returns the edited collection |
.query( queryString : Text ) : Collection .query( queryString : Text ; ...value : any ) : Collection .query( queryString : Text ; querySettings : Object ) : Collection returns all elements of a collection of objects that match the search conditions |
.reduce( formula : 4D.Function { ; initValue : any { ; ...param : expression }} ) : any .reduce( methodName : Text { ; initValue : any { ; ...param : expression }} ) : any 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 |
.reduceRight( formula : 4D.Function { ; initValue : any { ; ...param : expression }} ) : any .reduceRight( methodName : Text { ; initValue : any { ; ...param : expression }} ) : any applies the formula or methodName callback against an accumulator and each element in the collection (from right to left) to reduce it to a single value |
.remove( index : Integer { ; howMany : Integer } ) : Collection removes one or more element(s) from the specified index position in the collection and returns the edited collection |
.resize( size : Integer { ; defaultValue : any } ) : Collection sets the collection length to the specified new size and returns the resized collection |
.reverse( ) : Collection returns a deep copy of the collection with all its elements in reverse order |
.shift() : any removes the first element of the collection and returns it as the function result |
.slice( startFrom : Integer { ; end : Integer } ) : Collection returns a portion of a collection into a new collection |
.some( { startFrom : Integer ; } formula : 4D.Function { ; ...param : any } ) : Boolean .some( { startFrom : Integer ; } methodName : Text { ; ...param : any } ) : Boolean returns true if at least one element in the collection successfully passed a test implemented in the provided formula or methodName code |
.sort() : Collection .sort( formula : 4D.Function { ; ...extraParam : any } ) : Collection .sort( methodName : Text { ; ...extraParam : any } ) : Collection sorts the elements of the original collection and also returns the sorted collection |
.sum( { propertyPath : Text } ) : Real returns the sum for all values in the collection instance |
.unshift( value : any { ;...valueN : any } ) : Collection inserts the given value(s) at the beginning of the collection |
New collection
New collection {( ...value : any )} : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
value | Number, Text, Date, Time, Boolean, Object, Collection, Picture, Pointer | -> | Valor(es) de collection |
Result | Collection | <- | La nueva colección |
Descripción
El comando New collection
crea una nueva colección vacía o precargada y devuelve su referencia.
Si no se pasa ningún parámetro, New collection
crea una colección vacía y devuelve su referencia.
Debe asignar la referencia devuelta a una variable 4D del tipo Collection.
Keep in mind that
var : Collection
orC_COLLECTION
statements declare a variable of theCollection
type but do not create any collection.
Opcionalmente, puede prellenar la nueva colección pasando uno o varios valores como parámetro(s).
De lo contrario, puede añadir o modificar elementos posteriormente por asignación. Por ejemplo:
myCol[10]:="My new element"
Si el nuevo índice del elemento está más allá del último elemento existente de la colección, la colección se redimensiona automáticamente y a todos los nuevos elementos intermedios se les asigna un valor null.
Puede pasar cualquier número de valores de todos los tipos soportados (number, text, date, picture, pointer, object, collection...). A diferencia de los arrays, las colecciones pueden mezclar datos de diferentes tipos.
Debe prestar atención a los siguientes aspectos de la conversión:
- Si pasasun puntero, se mantiene "tal cual"; se evalúa utilizando el comando
JSON Stringify
- Las fechas se almacenan como fechas "aaaa-mm-dd" o de cadenas con el formato "AAAA-MM-DDTHH:mm:ss.SSSZ", según la configuración actual "fechas dentro de los objetos" de la base de datos. Al convertir las fechas 4D en texto antes de almacenarlas en la colección, por defecto el programa tiene en cuenta la zona horaria local. Puede modificar este comportamiento utilizando el selector
Dates inside objects
del comandoSET DATABASE PARAMETER
. - Si pasa un tiempo, se almacena como un número de milisegundos (Real).
Ejemplo 1
Quiere crear una nueva colección vacía y asignarla a una variable colección 4D:
var $myCol : Collection
$myCol:=New collection
//$myCol=[]
Ejemplo 2
Quiere crear una colección precargada:
var $filledColl : Collection
$filledColl:=New collection(33;"mike";"november";->myPtr;Current date)
//$filledColl=[33,"mike","november","->myPtr","2017-03-28T22:00:00.000Z"]
Ejemplo 3
Se crea una nueva colección y se añade un nuevo elemento:
var $coll : Collection
$coll:=New collection("a";"b";"c")
//$coll=["a","b","c"]
$coll[9]:="z" //añadir un décimo elemento con valor "z"
$vcolSize:=$coll.length //10
//$coll=["a","b","c",null,null,null,null,null,null,"z"]
New shared collection
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
New shared collection {( ...value : any )} : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
value | Number, Text, Date, Time, Boolean, Shared object, Shared collection | -> | Valor(es) de la collection compartida |
Result | Collection | <- | La nueva colección compartida |
Descripción
El comando New shared collection
crea una nueva colección compartida vacía o precargada y devuelve su referencia.
La adición de un elemento a esta colección utilizando el operador de asignación debe estar rodeada por la estructura Use...End use
, de lo contrario se genera un error (esto no es necesario cuando se añaden elementos utilizando funciones como push()
o map()
porque activan automáticamente una estructura interna Use...End use). Sin embargo, es posible leer un elemento sin una estructura Use...End use.
Para más información sobre las colecciones compartidas, por favor consulte la página Objetos y colecciones compartidas.
Si no se pasa ningún parámetro, New shared collection
crea una colección compartida vacía y devuelve su referencia.
Debe asignar la referencia devuelta a una variable 4D del tipo Collection.
Keep in mind that
var : Collection
orC_COLLECTION
statements declare a variable of theCollection
type but do not create any collection.
Optionally, you can prefill the new shared collection by passing one or several value(s) as parameter(s). De lo contrario, puede añadir o modificar elementos posteriormente por asignación notación objeto (ver ejemplo).
If the new element index is beyond the last existing element of the shared collection, the collection is automatically resized and all new intermediary elements are assigned a null value.
Puede pasar cualquier número de valores de los siguientes tipos soportados:
- number (real, longint...). Los valores numéricos se almacenan siempre como reales.
- text
- boolean
- date
- time (almacenado como número de milisegundos - 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.
Esta función modifica la colección original.
(*)Cuando un objeto o colección compartida se añade a una colección compartida, comparten el mismo identificador de bloqueo. For more information on this point, refer to 4D Doc Center.
Ejemplo
$mySharedCol:=New shared collection("alpha";"omega")
Use($mySharedCol)
$mySharedCol[1]:="beta"
End use
.at()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.at( index : Integer ) : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
index | Integer | -> | Índice del elemento a devolver |
Result | any | <- | El elemento en ese índice |
Descripción
The .at()
function returns the item at position index, allowing for positive and negative integers.
Esta función no modifica la colección original.
Los números enteros negativos cuentan hacia atrás desde el último elemento de la colección.
The function returns Undefined if index is beyond collection limits.
Ejemplo
var $col : Collection
$col:=New collection(10; 20; 30; 40; 50)
$element:=$col.at(0) // 10
$element:=$col.at(1) // 20
$element:=$col.at(-1) // 50
$element:=$col.at(-2) // 40
$element:=$col.at(10) // undefined
.average()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.average( {propertyPath : Text } ) : Real
Parámetros | Tipo | Descripción | |
---|---|---|---|
propertyPath | Text | -> | Ruta de la propiedad del objeto que se utilizará para el cálculo |
Result | Real, Undefined | <- | Media aritmética (promedio) de los valores de la colección |
Descripción
The .average()
function returns the arithmetic mean (average) of defined values in the collection instance.
Para el cálculo sólo se tienen en cuenta los elementos numéricos (se ignoran otros tipos de elementos).
If the collection contains objects, pass the propertyPath parameter to indicate the object property to take into account.
.average()
returns undefined
if:
- la colección está vacía,
- la colección no contiene elementos numéricos,
- propertyPath is not found in the collection.
Ejemplo 1
var $col : Collection
$col:=New collection(10;20;"Monday";True;6)
$vAvg:=$col.average() //12
Ejemplo 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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.clear() : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Collection | <- | Colección original con todos los elementos eliminados |
Descripción
The .clear()
function removes all elements from the collection instance and returns an empty collection.
Esta función modifica la colección original.
Ejemplo
var $col : Collection
$col:=New collection(1;2;5)
$col.clear()
$vSize:=$col.length //$vSize=0
.combine()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.combine( col2 : Collection {; index : Integer } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
col2 | Collection | -> | Colección a combinar |
index | Integer | -> | Posición a la que se deben combinar los elementos de inserción en la colección (por defecto=length+1) |
Result | Collection | <- | Colección original que contiene elementos combinados |
Descripción
The .combine()
function inserts col2 elements at the end or at the specified index position in the collection instance and returns the edited collection. Unlike the .insert()
function, .combine()
adds each value of col2 in the original collection, and not as a single collection element.
Esta función modifica la colección original.
By default, col2 elements are added at the end of the orginal collection. You can pass in index the position where you want the col2 elements to be inserted in the collection.
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.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.concat( value : any { ;...valueN } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
value | Number, Text, Object, Collection, Date, Time, Boolean, Picture | -> | Valores a concatenar. If value is a collection, all collection elements are added to the original collection |
Result | Collection | <- | Nueva colección con valor(es) añadido(s) a la colección original |
Descripción
The .concat()
function returns a new collection containing the elements of the original collection with all elements of the value parameter added to the end.
Esta función no modifica la colección original.
If value is a collection, all its elements are added as new elements at the end of the original collection. If value is not a collection, it is added itself as a new element.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
18 R3 | Nueva opción ck shared. New groupWith parameters |
v16 R6 | Añadidos |
.copy() : Collection
.copy( option : Integer ) : Collection
.copy( option : Integer ; groupWithCol : Collection ) : Collection
.copy( option : Integer ; groupWithObj : Object ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
option | Integer | -> | ck resolve pointers : resolve pointers before copying,ck shared : return a shared collection |
groupWithCol | Collection | -> | Colección compartida que se agrupa con la colección resultante |
groupWithObj | Object | -> | Objeto compartido que se agrupa con la colección resultante |
Result | Collection | <- | Copia profunda de la colección original |
Descripción
The .copy()
function returns a deep copy of the collection instance.Deep copy means that objects or collections within the original collection are duplicated and do not share any reference with the returned collection.
Esta función no modifica la colección original.
If passed, the option parameter can contain one of the following constants (or both):
option | Descripción |
---|---|
ck resolve pointers | Si la colección original contiene valores de tipo puntero, por defecto la copia también contiene los punteros. However, you can resolve pointers when copying by passing the ck resolve pointers constant. En este caso, cada puntero presente en la colección se evalúa al copiar y se utiliza su valor desreferenciado. |
ck shared | By default, copy() returns a regular (not shared) collection, even if the command is applied to a shared collection. Pass the ck shared constant to create a shared collection. In this case, you can use the groupWith parameter to associate the shared collection with another collection or object (see below). |
The groupWithCol or groupWithObj parameters allow you to designate a collection or an object with which the resulting collection should be associated.
Los objetos Datastore, dataclass y entity no son copiables. If .copy()
is called with them, Null
values are returned.
Ejemplo 1
We want to copy the $lastnames regular (non shared) collection into the $sharedObject shared object. To do this, we must create a shared copy of the collection ($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 es una colección estándar
$sharedLastnames:=$lastnames.copy(ck shared) //$sharedLastnames es una colección compartida
//Now we can put $sharedLastnames into $sharedObject
Use($sharedObject)
$sharedObject.lastnames:=$sharedLastnames
End use
Ejemplo 2
We want to combine $sharedColl1 and $sharedColl2. Dado que pertenecen a diferentes grupos compartidos, una combinación directa daría lugar a un error. Therefore, we must make a shared copy of $sharedColl1 and designate $sharedColl2 as a shared group for the copy.
var $sharedColl1;$sharedColl2;$copyColl : Collection
$sharedColl1:=New shared collection(New shared object("lastname";"Smith"))
$sharedColl2:=New shared collection(New shared object("lastname";"Brown"))
//$copyColl pertenece al mismo grupo compartido que $sharedColl2
$copyColl:=$sharedColl1.copy(ck shared;$sharedColl2)
Use($sharedColl2)
$sharedColl2.combine($copyColl)
End use
Ejemplo 3
We have a regular collection ($lastnames) and we want to put it in the Storage of the application. To do this, we must create a shared copy beforehand ($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 es una colección clásica
$sharedLastnames:=$lastnames.copy(ck shared) // copia compartida
Use(Storage)
Storage.lastnames:=$sharedLastnames
End use
Ejemplo 4
This example illustrates the use of the ck resolve pointers
option:
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) //muestra "Hello World!"
$what:="You!"
$col3:=$col2.copy(ck resolve pointers)
ALERT($col3[0].alpha+" "+$col3[1].what) //muestra "Hello You!"
.count()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.count( { propertyPath : Text } ) : Real
Parámetros | Tipo | Descripción | |
---|---|---|---|
propertyPath | Text | -> | Ruta de la propiedad del objeto que se utilizará para el cálculo |
Result | Real | <- | Número de elementos en la colección |
Descripción
The .count()
function returns the number of non-null elements in the collection.
If the collection contains objects, you can pass the propertyPath parameter. In this case, only elements that contain the propertyPath are taken into account.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.countValues( value : any {; propertyPath : Text } ) : Real
Parámetros | Tipo | Descripción | |
---|---|---|---|
value | Text, Number, Boolean, Date, Object, Collection | -> | Valor a contar |
propertyPath | Text | -> | Ruta de la propiedad del objeto que se utilizará para el cálculo |
Result | Real | <- | Número de ocurrencias del valor |
Descripción
The .countValues()
function returns the number of times value is found in the collection.
You can pass in value:
- un valor escalar (texto, número, booleano, fecha),
- una referencia de objeto o de colección.
For an element to be found, the type of value must be equivalent to the type of the element; the method uses the equality operator.
The optional propertyPath parameter allows you to count values inside a collection of objects: pass in propertyPath the path of the property whose values you want to count.
Esta función no modifica la colección original.
Ejemplo 1
var $col : Collection
var $vCount : Integer
$col:=New collection(1;2;5;5;5;3;6;4)
$vCount:=$col.countValues(5) // $vCount=3
Ejemplo 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
Ejemplo 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()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Support of ck count values |
v16 R6 | Añadidos |
.distinct( {options : Integer} ) : Collection
.distinct( propertyPath : Text {; options : Integer } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
propertyPath | Text | -> | Ruta del atributo cuyos valores distintos desea obtener |
options | Integer | -> | ck diacritical , ck count values |
Result | Collection | <- | Nueva colección con sólo valores distintos |
Descripción
The .distinct()
function returns a collection containing only distinct (different) values from the original collection.
Esta función no modifica la colección original.
La colección devuelta se clasifica automáticamente. Null values are not returned.
If the collection contains objects, you can pass the propertyPath parameter to indicate the object property whose distinct values you want to get.
In the options parameter, you can pass one or a combination of the following constants:
Constante | Valor | Comentario |
---|---|---|
ck diacritical | 8 | La evaluación distingue entre mayúsculas y minúsculas y diferencia los caracteres acentuados. Por defecto si se omite, se realiza una evaluación no diacrítica |
ck count values | 32 | Devuelve el conteo de elementos para cada valor distinto. When this option is passed, .distinct() returns a collection of objects containing a pair of {"value":*value*;"count":*count*} attributes. |
Ejemplos
var $c; $c2; $c3 : 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]
$c3:=$c.distinct("size";ck count values) //$c3=[{value:1,count:2},{value:3,count:1}]
.equal()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.equal( collection2 : Collection {; option : Integer } ) : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
collection2 | Collection | -> | Colección a comparar |
option | Integer | -> | ck diacritical : diacritical evaluation ("A" # "a" for example) |
Result | Boolean | <- | True si las colecciones son idénticas, false en caso contrario |
Descripción
The .equal()
function recursively compares the contents of the collection and collection2 (deep comparison)and returns true if they are identical.
Por defecto, se realiza una evaluación no diacrítica. If you want the evaluation to be case sensitive or to differentiate accented characters, pass the ck diacritical
constant in the option parameter.
Elements with Null values are not equal to Undefined elements.
A recursive comparison of collections can be time-consuming if the collection is large and deep. If you only want to compare two collection references, you may consider using the =
comparison operator for collection references.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R6 | Soporte de fórmula |
v16 R6 | Añadidos |
.every( { startFrom : Integer ; } formula : 4D.Function { ;...param : any } ) : Boolean
.every( { startFrom : Integer ; } methodName : Text { ;...param : any } ) : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
startFrom | Integer | -> | Índice para iniciar la prueba en |
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
param | any | -> | Parameter(s) to pass to formula or methodName |
Result | Boolean | <- | True si todos los elementos han pasado la prueba con éxito |
Descripción
The .every()
function returns true if all elements in the collection successfully passed a test implemented in the provided formula object or methodName method.
Se designa la retrollamada a ejecutar para evaluar los elementos de la colección utilizando:
- 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).
La retrollamada recibe los siguientes parámetros:
- in $1.value: element value to be evaluated
- en $2: param
- en $N...: paramN...
Puede definir los siguientes parámetros:
- (mandatory if you used a method) $1.result (Boolean): true if the element value evaluation is successful, false otherwise.
- $1.stop (Boolean, optional): true to stop the method callback. El valor devuelto es el último calculado.
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, .every()
tests the whole collection. Optionally, you can pass in startFrom the index of the element from which to start the test.
- 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 ( startFrom:=startFrom+length).
- If startFrom = 0, the whole collection is searched (default).
Ejemplo 1
var $c : Collection
var $b : Boolean
var $f : 4D.Function
$f:=Formula($1.value>0)
$c:=New collection
$c.push(5;3;1;4;6;2)
$b:=$c.every($f) //devuelve true
$c.push(-1)
$b:=$c.every($f) //devuelve false
Ejemplo 2
Este ejemplo comprueba que todos los elementos de una colección son de 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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.extract( propertyPath : Text { ; option : Integer } ) : Collection
.extract( propertyPath : Text ; targetPath : Text { ;...propertyPathOrTargetPathN : Text } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
propertyPath | Text | -> | Ruta de la propiedad del objeto cuyos valores deben ser extraídos a la nueva colección |
targetpath | Text | -> | Ruta de la propiedad de destino o nombre de la propiedad |
option | Integer | -> | ck keep null : include null properties in the returned collection (ignored by default). Parameter ignored if targetPath passed. |
Result | Collection | <- | Nueva colección que contiene los valores extraídos |
Descripción
The .extract()
function creates and returns a new collection containing propertyPath values extracted from the original collection of objects.
Esta función no modifica la colección original.
The contents of the returned collection depends on the targetPath parameter:
If the targetPath parameter is omitted,
.extract()
populates the new collection with the propertyPath values of the original collection.By default, elements for which propertyPath is null or undefined are ignored in the resulting collection. You can pass the
ck keep null
constant in the option parameter to include these values as null elements in the returned collection.If one or more targetPath parameter(s) are passed (corresponding to one or more propertyPath parameter(s)),
.extract()
populates the new collection with the propertyPath properties and each element of the new collection is an object with targetPath properties filled with the matching propertyPath properties. Null values are kept (option parameter is ignored with this syntax).
Ejemplo 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]
Ejemplo 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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.fill( value : any ) : Collection
.fill( value : any ; startFrom : Integer { ; end : Integer } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
value | number, Text, Collection, Object, Date, Boolean | -> | Valor a asignar |
startFrom | Integer | -> | Índice de inicio (incluido) |
end | Integer | -> | Índice final (no incluido) |
Result | collection | <- | Colección original con valores rellenados |
Descripción
The .fill()
function fills the collection with the specified value, optionally from startFrom index to end index, and returns the resulting collection.
Esta función modifica la colección original.
- If the startFrom parameter is omitted, value is set to all collection elements (startFrom=0).
- If the startFrom parameter is passed and end omitted, value is set to collection elements starting at startFrom to the last element of the collection (end=length).
- If both the startFrom parameter and end are passed, value is set to collection elements starting at startFrom to the element end.
En caso de incoherencia, se aplican las siguientes reglas:
- If startFrom < 0, it is recalculated as startFrom:=startFrom+length (it is considered as the offset from the end of the collection). If the calculated value is negative, startFrom is set to 0.
- If end < 0 , it is recalculated as end:=end+length.
- If end < startFrom (passed or calculated values), the method does nothing.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R6 | Soporte de fórmula |
v16 R6 | Añadidos |
.filter( formula : 4D.Function { ; ...param : any } ) : Collection
.filter( methodName : Text { ; ...param : any } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
param | any | -> | Parameter(s) to pass to formula or methodName |
Result | Collection | <- | Nueva colección que contiene elementos filtrados (copia superficial) |
Descripción
The .filter()
function returns a new collection containing all elements of the original collection for which the formula or methodName result is true. This function returns a shallow copy, which means that objects or collections in both collections share the same reference. Si la colección original es una colección compartida, la colección devuelta es también una colección compartida.
Esta función no modifica la colección original.
Se designa la retrollamada a ejecutar para filtrar los elementos de la colección utilizando:
- 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) and an object in first parameter ($1). The callback can perform any test, with or without the parameter(s) and must return true for each element fulfilling the condition and thus, to push to the new collection.
La retrollamada recibe los siguientes parámetros:
- in $1.value: element value to be evaluated
- en $2: param
- en $N...: paramN...
Puede definir los siguientes parámetros:
- $1.result (Boolean): true if the element value matches the filter condition and must be kept, false otherwise.
- $1.stop (Boolean, optional): true to stop the method callback. El valor devuelto es el último calculado.
When using methodName as callback, and if the method does not return any value, .filter()
will look at the property $1.result that you must set to true for each element fulfilling the condition.
Ejemplo 1
Desea obtener la colección de elementos de texto cuya longitud es inferior a 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"]
Ejemplo 2
Quiere filtrar los elementos según su 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()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R6 | Soporte de fórmula |
v16 R6 | Añadidos |
.find( { startFrom : Integer ; } formula : 4D.Function { ; ...param : any } ) : any
.find( { startFrom : Integer ; } methodName : Text { ; ...param : any } ) : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
startFrom | Integer | -> | Índice para iniciar la búsqueda en |
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
param | any | -> | Parameter(s) to pass to formula or methodName |
Result | any | <- | Primer valor encontrado, o Undefined si no se encuentra |
Descripción
The .find()
function returns the first value in the collection for which formula or methodName result, applied on each element, returns true.
Esta función no modifica la colección original.
Se designa la retrollamada a ejecutar para evaluar los elementos de la colección utilizando:
- 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 the first element fulfilling the condition. It receives an Object
in first parameter ($1).
La retrollamada recibe los siguientes parámetros:
- in $1.value: element value to be evaluated
- en $2: param
- en $N...: paramN...
Puede definir los siguientes parámetros:
- (mandatory if you used a method) $1.result (Boolean): true if the element value matches the search condition, false otherwise.
- $1.stop (Boolean, optional): true to stop the method callback. El valor devuelto es el último calculado.
By default, .find()
searches in the whole collection. Optionally, you can pass in startFrom the index of element from which to start the search.
- 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).
Ejemplo 1
Quiere obtener el primer elemento de texto con una longitud menor que 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"
Ejemplo 2
Quiere encontrar el nombre de una ciudad dentro de una colección:
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()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R6 | Soporte de fórmula |
v16 R6 | Añadidos |
.findIndex( { startFrom : Integer ; } formula : 4D.Function { ; ...param : any } ) : Integer
.findIndex( { startFrom : Integer ; } methodName : Text { ; ...param : any } ) : Integer
Parámetros | Tipo | Descripción | |
---|---|---|---|
startFrom | Integer | -> | Índice para iniciar la búsqueda en |
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
param | any | -> | Parameter(s) to pass to formula or methodName |
Result | Integer | <- | Índice del primer valor encontrado, o -1 si no se encuentra |
Descripción
The .findIndex()
function returns the index, in the collection, of the first value for which formula or methodName, applied on each element, returns true.
Esta función no modifica la colección original.
Se designa la retrollamada a ejecutar para evaluar los elementos de la colección utilizando:
- 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 can perform any test, with or without the parameter(s) and must return true for the first element fulfilling the condition. It receives an Object
in first parameter ($1).
La retrollamada recibe los siguientes parámetros:
- in $1.value: element value to be evaluated
- en $2: param
- en $N...: paramN...
Puede definir los siguientes parámetros:
- (mandatory if you used a method) $1.result (Boolean): true if the element value matches the search condition, false otherwise.
- $1.stop (Boolean, optional): true to stop the method callback. El valor devuelto es el último calculado.
By default, .findIndex()
searches in the whole collection. Optionally, you can pass in startFrom the index of element from which to start the search.
- 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).
Ejemplo
Quiere encontrar la posición del primer nombre de ciudad dentro de una colección:
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
.first()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.first() : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | any | <- | Primer elemento de la colección |
Descripción
The .first()
function returns the first element of the collection.
Esta función no modifica la colección original.
La función devuelve Undefined si la colección está vacía.
Ejemplo
var $col; $emptyCol : Collection
var $first : Variante
$col:=New collection(10; 20; 30; "hello"; 50)
$first:=$col.first() // 10
$emptyCol:=New collection() //vacío
// $first:=$emptyCol[0] //daría error
$first:=$emptyCol.first() // devuelve Undefined
.flat()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.flat( { depth : Integer } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
depth | Integer | -> | A qué profundidad debe aplanarse una estructura de colección anidada. Por defecto=1 |
Result | Collection | <- | Colección aplanada |
Descripción
The .flat()
function creates a new collection with all sub-collection elements concatenated into it recursively up to the specified depth.
By default, if the depth parameter is omitted, only the first level of the nested collection structure will be flattened.
Esta función no modifica la colección original.
Ejemplo
$col:=New collection(1; 2; New collection(3; 4))
$col.flat()
// [1, 2, 3, 4]
$col:=New collection(1; 2; New collection(3; 4; New collection(5; 6)))
$col.flat()
// [1, 2, 3, 4, [5, 6]]
$col:=New collection(1; 2; New collection(3; 4; New collection(5; 6)))
$col.flat(2)
// [1, 2, 3, 4, 5, 6]
$col:=New collection(1; 2; New collection(3; 4; 5; 6; New collection(7; 8; New collection(9; 10))))
$col.flat(MAXLONG)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.flatMap()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.flatMap( formula : 4D.Function { ; ...param : any } ) : Collection
.flatMap( methodName : Text { ; ...param : any } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
param | any | -> | Parameter(s) to pass to formula or methodName |
Result | Collection | <- | Colección de valores transformados y aplanados en una profundidad de 1 |
Descripción
The .flatMap()
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 and flattened by a depth of 1. Optionally, you can pass parameters to formula or methodName using the param parameter(s).
This function is identical to a map()
call followed by a flat()
call of depth 1.
Esta función no modifica la colección original.
Se designa la retrollamada a ejecutar para evaluar los elementos de la colección utilizando:
- 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).
La retrollamada recibe los siguientes parámetros:
- in $1.value: element value to be evaluated
- en $2: param
- en $N...: paramN...
Puede definir los siguientes parámetros:
- (mandatory if you used a method) $1.result (any type): new transformed value to add to the resulting collection
- $1.stop (Boolean, optional): true to stop the method callback. El valor devuelto es el último calculado.
Ejemplo 1
var $col ; $result : Collection
$col:=New collection(1; 2; 3; 4)
$result:=$col.map(Formula(New collection($1.value*2))
// [[2],[4],[6],[8]]
$result:=$col.flatMap(Formula(New collection($1.value*2))
// [2,4,6,8]
Ejemplo 2
var $col; $result : Collection
$col:=New collection("Hello how"; ""; "are you ?")
$result:=$col.map(Formula(Split string($1.value; " ")))
// [["Hello", "how"], [], ["are", "you", "?"]]
$result:=$col.flatMap(Formula(Split string($1.value; " ")))
// ["Hello", "how", "are", "you", "?"]
Ejemplo 3
Desea calcular el porcentaje de cada valor de la colección con respecto al total:
var $c; $c2 : Collection
var $f : 4D.Function
$c:=New collection(1; 4; 9; 10; 20)
$f:=Formula(New collection($1.value;Round(($1.value/$2)*100; 2)))
$c2:=$c.flatMap($f; $c.sum())
//$c2=[1, 2.27, 4, 9.09,9, 20.45,10, 22.73, 20, 45.45]
.includes()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.includes( toSearch : expression { ; startFrom : Integer } ) : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
toSearch | expresión | -> | Expresión a buscar en la colección |
startFrom | Integer | -> | Índice para iniciar la búsqueda en |
Result | Boolean | <- | True if toSearch is found in the collection |
Descripción
The .includes()
function returns True if the toSearch expression is found among collection elements, otherwise False.
Esta función no modifica la colección original.
In toSearch, pass the expression to find in the collection. Puede pasar:
- un valor escalar (texto, número, booleano, fecha),
- el valor null,
- una referencia de objeto o de colección.
toSearch must match exactly the element to find (the same rules as for the equality operator of the data type are applied).
Optionally, you can pass the index of collection from which to start the search in startFrom.
- If startFrom >= collection's length, False 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 that even if startFrom is negative, the collection is still searched from left to right.
- If startFrom = 0, the whole collection is searched (default).
Ejemplo
var $col : Collection
var $in : Boolean
var $obj : Object
$obj:=New object("value"; 10)
$col:=New collection(1;2;"Henry";5;3;"Albert";6;4;"Alan";5;$obj)
$in:=$col.includes(3) //True
$in:=$col.includes(5;6) //True
$in:=$col.includes("al@") //True
$in:=$col.includes("Hello") //False
$in:=$col.includes($obj) //True
$in:=$col.includes(New object("value"; 10)) //False
.indexOf()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.indexOf( toSearch : expression { ; startFrom : Integer } ) : Integer
Parámetros | Tipo | Descripción | |
---|---|---|---|
toSearch | expresión | -> | Expresión a buscar en la colección |
startFrom | Integer | -> | Índice para iniciar la búsqueda en |
Result | Integer | <- | Índice de la primera ocurrencia de toSearch en la colección, -1 si no se encuentra |
Descripción
The .indexOf()
function searches the toSearch expression among collection elements and returns the index of the first found occurrence, or -1 if it was not found.
Esta función no modifica la colección original.
In toSearch, pass the expression to find in the collection. Puede pasar:
- un valor escalar (texto, número, booleano, fecha),
- el valor null,
- una referencia de objeto o de colección.
toSearch must match exactly the element to find (the same rules as for the equality operator of the data type are applied).
Optionally, you can pass the index of collection from which to start the search in startFrom.
- 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).
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.indices( queryString : Text { ; ...value : any } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
queryString | Text | -> | Criterio de búsqueda |
value | any | -> | Valor(es) a comparar cuando se utiliza(n) marcador(es) de posición |
Result | Collection | <- | Element index(es) matching queryString in the collection |
Descripción
The .indices()
function works exactly the same as the .query()
function but returns indexes, in the original collection, of object collection elements that match the queryString search conditions, and not elements themselves. Los índices se devuelven en orden ascendente.
Esta función no modifica la colección original.
The queryString parameter uses the following syntax:
propertyPath comparator value {logicalOperator propertyPath comparator value}
For a detailed description of the queryString and value parameters, please refer to the dataClass.query()
function.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.insert( index : Integer ; element : any ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
index | Integer | -> | Dónde insertar el elemento |
element | any | -> | Elemento a insertar en la colección |
Result | Collection | <- | Colección original que contiene los elementos insertados |
Descripción
The .insert()
function inserts element at the specified index position in the collection instance and returns the edited collection.
Esta función modifica la colección original.
In index, pass the position where you want the element to be inserted in the collection.
Warning: Keep in mind that collection elements are numbered from 0.
- If index > the length of the collection, 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).
- Si el valor calculado es negativo, index toma el valor 0.
Se puede insertar cualquier tipo de elemento aceptado por una colección, incluso otra colección.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.join( delimiter : Text { ; option : Integer } ) : Text
Parámetros | Tipo | Descripción | |
---|---|---|---|
delimiter | Text | -> | Separador a utilizar entre elementos |
option | Integer | -> | ck ignore null or empty : ignore null and empty strings in the result |
Result | Text | <- | Cadena que contiene todos los elementos de la colección, separados por un delimitador |
Descripción
The .join()
function converts all elements of the collection to strings and concatenates them using the specified delimiter string as separator.The function returns the resulting string.
Esta función no modifica la colección original.
Por defecto, los elementos nulos o vacíos de la colección se devuelven en la cadena resultante. Pass the ck ignore null or empty
constant in the option parameter if you want to remove them from the resulting string.
Ejemplo
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
.last()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.last() : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | any | <- | Último elemento de la colección |
Descripción
The .last()
function returns the last element of the collection.
Esta función no modifica la colección original.
La función devuelve Undefined si la colección está vacía.
Ejemplo
var $col; $emptyCol : Collection
var $last : Variant
$col:=New collection(10; 20; 30; "hello"; 50)
$last:=$col.last() // 50
$emptyCol:=New collection() //empty
// $last:=$emptyCol[$emptyCol.length-1] //devuelve un error
$last:=$emptyCol.last() // devuelve Indefinido
.lastIndexOf()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.lastIndexOf( toSearch : expression { ; startFrom : Integer } ) : Integer
Parámetros | Tipo | Descripción | |
---|---|---|---|
toSearch | expresión | -> | El elemento que se va a buscar dentro de la colección |
startFrom | Integer | -> | Índice para iniciar la búsqueda en |
Result | Integer | <- | Índice de la última ocurrencia de toSearch en la colección, -1 si no se encuentra |
Descripción
The .lastIndexOf()
function searches the toSearch expression among collection elements and returns the index of the last occurrence, or -1 if it was not found.
Esta función no modifica la colección original.
In toSearch, pass the expression to find in the collection. Puede pasar:
- un valor escalar (texto, número, booleano, fecha),
- el valor null,
- una referencia de objeto o de colección.
toSearch must match exactly the element to find (the same rules as for the equality operator are applied).
Optionally, you can pass the index of collection from which to start a reverse search in startFrom.
- If startFrom >= the collection's length minus one (coll.length-1), the whole collection is searched (default).
- If startFrom < 0, it is recalculated as startFrom:=startFrom+length (it is considered as the offset from the end of the collection). Si el valor calculado es negativo, se devuelve -1 (no se busca en la colección). Note: Even if startFrom is negative, the collection is still searched from right to left.
- If startFrom = 0, -1 is returned, which means the collection is not searched.
Ejemplo
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") //devuelve 12
$pos2:=$col.lastIndexOf("e";6) //devuelve 4
$pos3:=$col.lastIndexOf("e";15) //devuelve 12
$pos4:=$col.lastIndexOf("e";-2) //devuelve 10
$pos5:=$col.lastIndexOf("x") //devuelve -1
.length
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R5 | Añadidos |
.length : Integer
Descripción
The .length
property returns the number of elements in the collection.
The .length
property is initialized when the collection is created. Añadir o eliminar elementos actualiza la longitud, si es necesario. This property is read-only (you cannot use it to set the size of the collection).
Ejemplo
var $col : Collection //$col.length inicializada en 0
$col:=New collection("one";"two";"three") //$col.length actualizada a 3
$col[4]:="five" //$col.length actualizada a 5
$vSize:=$col.remove(0;3).length //$vSize=2
.map()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R6 | Soporte de fórmula |
v16 R6 | Añadidos |
.map( formula : 4D.Function { ; ...param : any } ) : Collection
.map( methodName : Text { ; ...param : any } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
param | any | -> | Parameter(s) to pass to formula or methodName |
Result | Collection | <- | Colección de valores transformados |
Descripción
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()
always returns a collection with the same size as the original collection, except if $1.stop was used (see below).
Esta función no modifica la colección original.
Se designa la retrollamada a ejecutar para evaluar los elementos de la colección utilizando:
- 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).
La retrollamada recibe los siguientes parámetros:
- in $1.value: element value to be evaluated
- en $2: param
- en $N...: paramN...
Puede definir los siguientes parámetros:
- (mandatory if you used a method) $1.result (any type): new transformed value to add to the resulting collection
- $1.stop (Boolean, optional): true to stop the method callback. El valor devuelto es el último calculado.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.max( { propertyPath : Text } ) : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
propertyPath | Text | -> | Ruta de la propiedad del objeto que se utilizará para la evaluación |
Result | Boolean, Text, Number, Collection, Object, Date | <- | Valor máximo en la colección |
Descripción
The .max()
function returns the element with the highest value in the collection (the last element of the collection as it would be sorted in ascending order using the .sort()
function).
Esta función no modifica la colección original.
If the collection contains different types of values, the .max()
function will return the maximum value within the last element type in the type list order (see .sort()
description).
If the collection contains objects, pass the propertyPath parameter to indicate the object property whose maximum value you want to get.
If the collection is empty, .max()
returns Undefined.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.min( { propertyPath : Text } ) : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
propertyPath | Text | -> | Ruta de la propiedad del objeto que se utilizará para la evaluación |
Result | Boolean, Text, Number, Collection, Object, Date | <- | Valor mínimo en la colección |
Descripción
The .min()
function returns the element with the smallest value in the collection (the first element of the collection as it would be sorted in ascending order using the .sort()
function).
Esta función no modifica la colección original.
If the collection contains different types of values, the .min()
function will return the minimum value within the first element type in the type list order (see .sort()
description).
If the collection contains objects, pass the propertyPath parameter to indicate the object property whose minimum value you want to get.
If the collection is empty, .min()
returns Undefined.
Ejemplo
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"
.multiSort()
Historia
Lanzamiento | Modificaciones |
---|---|
20 R3 | Añadidos |
.multiSort() : Collection
.multiSort( colsToSort : Collection ) : Collection
.multiSort( formula : 4D.Function ; colsToSort : Collection ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
formula | 4D.Function | -> | Objeto fórmula |
colsToSort | Collection | -> | Collection of collections and/or objects with {collection :colToSort;order :ck ascending or ck descending } properties |
Result | Collection | <- | Colección original ordenada |
Descripción
The .multiSort()
function enables you to carry out a multi-level synchronized sort on a set of collections.
This function modifies the original collection as well as all collections used in colsToSort parameter.
If .multiSort()
is called with no parameters, the function has the same effect as the .sort()
function: the collection is sorted (only scalar values) in ascending order by default, according to their type. Si la colección contiene valores de diferentes tipos, se agrupan primero por tipo y se ordenan después. Si attributePath lleva a una propiedad de objeto que contiene valores de diferentes tipos, primero se agrupan por tipo y se ordenan después.
- null
- booleans
- cadenas
- numbers
- objects
- collections
- dates
Ordenación sincronizada de un nivel
To sort several collections synchronously, just pass in colsToSort a collection of collections to sort. Puede pasar un número ilimitado de colecciones. The original collection will be sorted in ascending order and all colsToSort collections will be sorted in a synchronized manner.
All colsToSort collections must have the same number of elements, otherwise an error is returned.
If you want to sort the collections in some other order than ascending, you must supply a formula (Formula object that defines the sort order. The return value should be a boolean that indicates the relative order of the two elements: True if $1.value is less than $1.value2, False if $1.value is greater than $1.value2. Puede ofrecer parámetros adicionales a la fórmula si es necesario.
La fórmula recibe los siguientes parámetros:
- $1 (objeto), donde:
- $1.value (any type): first element value to be compared
- $1.value2 (any type): second element value to be compared
- $2...$N (cualquier tipo): parámetros adicionales
Ordenación sincronizada multinivel
Defining a multi-level synchronized sort requires that you pass an object containing {collection
:colToSort;order
:ck ascending
or ck descending
} properties instead of the colToSort itself for every collection to use as sub-level.
The sort levels are determined by the order in which the collections are passed in the colsToSort parameter: the position of a collection
/order
object in the syntax determines its sort level.
The .multiSort()
function uses a stable sort algorithm.
Ejemplo 1
Una simple ordenación sincronizada de colecciones con diferentes tipos de valores:
var $col;$col2;$col3 : Collection
$col:=["A"; "C"; "B"]
$col2:=[1; 2; 3]
$col3:=[["Jim"; "Philip"; "Maria"]; ["blue"; "green"]; ["11"; 22; "33"]]
$col.multiSort([$col2; $col3])
//$col=["A","B","C"]
//$col2=[1,3,2]
//$col3[0]=["Jim","Philip","Maria"]
//$col3[1]=["11",22,"33"]
//$col3[2]=["blue","green"]
Ejemplo 2
Desea ordenar tres colecciones sincronizadas: city, country y continent. Quiere una ordenación ascendente de la primera y la tercera colección y sincronización para la segunda colección:
var $city : Collection
var $country : Collection
var $continent : Collection
$city:=["Paris"; "Lyon"; "Rabat"; "Eching"; "San Diego"]
$country:=["France"; "France"; "Morocco"; "Germany"; "US"]
$continent:=["Europe"; "Europe"; "Africa"; "Europe"; "America"]
$continent.multiSort([$country; {collection: $city; order: ck ascending}])
//$continent=["Africa","America","Europe","Europe","Europe"]
//$country=["Morocco","US","France","France","Germany"]
//$city=["Rabat","San Diego","Lyon","Paris","Eching"]
Ejemplo 3
También puede sincronizar colecciones de objetos.
var $name : Collection
var $address : Collection
$name:=[]
$name.push({firstname: "John"; lastname: "Smith"})
$name.push({firstname: "Alain"; lastname: "Martin"})
$name.push({firstname: "Jane"; lastname: "Doe"})
$name.push({firstname: "John"; lastname: "Doe"})
$address:=[]
$address.push({city: "Paris"; country: "France"})
$address.push({city: "Lyon"; country: "France"})
$address.push({city: "Eching"; country: "Germany"})
$address.push({city: "Berlin"; country: "Germany"})
$name.multiSort(Formula($1.value.firstname<$1.value2.firstname); [$address])
//"Alain Martin","Jane Doe","John Smith","John Doe"
//"Lyon France","Eching Germany","Paris France","Berlin Germany"
.orderBy()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.orderBy( ) : Collection
.orderBy( pathStrings : Text ) : Collection
.orderBy( pathObjects : Collection ) : Collection
.orderBy( ascOrDesc : Integer ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
pathStrings | Text | -> | Ruta(s) de propiedad(es) a utilizar para ordenar la colección |
pathObjects | Collection | -> | Colección de objetos criterio |
ascOrDesc | Integer | -> | ck ascending o ck descending (valores escalares) |
Result | Collection | <- | Copia ordenada de la colección (copia superficial) |
Descripción
The .orderBy()
function returns a new collection containing all elements of the collection in the specified order.
This function returns a shallow copy, which means that objects or collections in both collections share the same reference. Si la colección original es una colección compartida, la colección devuelta es también una colección compartida.
Esta función no modifica la colección original.
Si no se pasa ningún parámetro, la función ordena los valores escalares de la colección en orden ascendente (otros tipos de elementos como objetos o colecciones se devuelven con un orden interno). You can modify this automatic order by passing the ck ascending
or ck descending
constants in the ascOrDesc parameter (see below).
También puede pasar un parámetro de criterios para definir cómo deben ordenarse los elementos de la colección. Se admiten tres sintaxis para este parámetro:
pathStrings : Text (formula). Syntax:
propertyPath1 {desc or asc}, propertyPath2 {desc or asc},...
(default order: asc). pathStrings contains a formula made of 1 to x property paths and (optionally) sort orders, separated by commas. El orden en que se pasan las propiedades determina la prioridad de ordenación de los elementos de la colección. Por defecto, las propiedades se clasifican en orden ascendente. Puede definir el orden de clasificación de una propiedad en la cadena de criterios, separado de la ruta de la propiedad por un solo espacio: pase "asc" para ordenar en orden ascendente o "desc" en orden descendente.pathObjects : Collection. You can add as many objects in the pathObjects collection as necessary. Por defecto, las propiedades se clasifican en orden ascendente ("descending" es false). Cada elemento de la colección contiene un objeto estructurado de la siguiente manera:
{
"propertyPath": string,
"descending": boolean
}
ascOrDesc : Integer. You pass one of the following constants from the Objects and collections theme:
Constante Tipo Valor Comentario ck ascending Longint 0 Los elementos se ordenan de forma ascendente (por defecto) ck descending Longint 1 Los elementos se ordenan de forma descendente Esta sintaxis sólo ordena los valores escalares de la colección (otros tipos de elementos, como objetos o colecciones, se devuelven desordenados).
Si la colección contiene elementos de diferentes tipos, se agrupan primero por tipo y se ordenan después. Si attributePath lleva a una propiedad de objeto que contiene valores de diferentes tipos, primero se agrupan por tipo y se ordenan después.
- null
- booleans
- cadenas
- numbers
- objects
- collections
- dates
Ejemplo 1
Ordenar una colección de números de forma ascendente y descendente:
var $c; $c2; $c3 : Collection
$c:=New collection
For($vCounter;1;10)
$c.push(Random)
End for
$c2:=$c.orderBy(ck ascending)
$c3:=$c.orderBy(ck descending)
Ejemplo 2
Ordenar una colección de objetos a partir de una fórmula de texto con nombres de propiedades:
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 una colección de objetos con una ruta de propiedades:
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")
Ejemplo 3
Ordenar una colección de objetos utilizando una colección de objetos criterio:
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 con una ruta de propiedad:
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()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R6 | Soporte de fórmula |
v16 R6 | Añadidos |
.orderByMethod( formula : 4D.Function { ; ...extraParam : expression } ) : Collection
.orderByMethod( methodName : Text { ; ...extraParam : expression } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
extraParam | any | -> | Parámetro(s) a pasar |
Result | Collection | <- | Copia ordenada de la colección (copia superficial) |
Descripción
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.
This function returns a shallow copy, which means that objects or collections in both collections share the same reference. Si la colección original es una colección compartida, la colección devuelta es también una colección compartida.
Esta función no modifica la colección original.
Se designa la retrollamada a ejecutar para evaluar los elementos de la colección utilizando:
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.
La retrollamada recibe los siguientes parámetros:
- $1 (objeto), donde:
- $1.value (any type): first element value to be compared
- $1.value2 (any type): second element value to be compared
- $2...$N (cualquier tipo): parámetros adicionales
Si utilizó un método, debe definir el siguiente parámetro:
- $1.result (boolean): true if $1.value < $1.value2, false otherwise
Ejemplo 1
Desea ordenar una colección de cadenas en orden numérico en lugar de orden alfabético:
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"]
Ejemplo 2
Quiere ordenar una colección de cadenas según su longitud:
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]
Ejemplo 3
Ordenar los elementos de la colección por código de caracteres o alfabéticamente:
var $strings1; $strings2 : Collection
$strings1:=New collection("Alpha";"Charlie";"alpha";"bravo";"Bravo";"charlie")
//utilizando el código de caracteres:
$strings2:=$strings1.orderByMethod(Function(sortCollection);sk character codes)
// result : ["Alpha","Bravo","Charlie","alpha","bravo","charlie"]
//utilizando el lenguaje:
$strings2:=$strings1.orderByMethod(Function(sortCollection);sk strict)
// resultado : ["alpha","Alpha","bravo","Bravo","charlie","Charlie"]
The sortCollection method:
var $1 : Object
var $2: Integer // opción de ordenación
$1.result:=(Compare strings($1.value;$1.value2;$2)<0)
.pop()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.pop() : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | any | <- | Último elemento de la colección |
Descripción
The .pop()
function removes the last element from the collection and returns it as the function result.
Esta función modifica la colección original.
When applied to an empty collection, .pop()
returns undefined.
Ejemplo
.pop()
, used in conjunction with .push()
, can be used to implement a first-in, last-out stack feature:
var $stack : Collection
$stack:=New collection //$stack=[]
$stack.push(1;2) //$stack=[1,2]
$stack.pop() //$stack=[1] Devuelve 2
$stack.push(New collection(4;5)) //$stack=[[1,[4,5]]
$stack.pop() //$stack=[1] Devuelve [4,5]
$stack.pop() //$stack=[] Devuelve 1
.push()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.push( element : any { ;...elementN } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
element | any | -> | Elemento(s) a añadir a la colección |
Result | Collection | <- | Colección original que contiene los elementos añadidos |
Descripción
The .push()
function appends one or more element(s) to the end of the collection instance and returns the edited collection.
Esta función modifica la colección original.
Ejemplo 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}
Ejemplo 2
Desea ordenar la colección 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()
Historia
Lanzamiento | Modificaciones |
---|---|
20 R6 | Support of queries using object or collection references |
17 R5 | Soporte de querySettings |
v16 R6 | Añadidos |
.query( queryString : Text ) : Collection
.query( queryString : Text ; ...value : any ) : Collection
.query( queryString : Text ; querySettings : Object ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
queryString | Text | -> | Criterio de búsqueda |
value | any | -> | Valor(es) a comparar cuando se utiliza(n) marcador(es) de posición |
querySettings | Object | -> | Opciones de búsqueda: parámetros, atributos |
Result | Collection | <- | Elemento(s) que coincide(n) con queryString en la colección |
Descripción
The .query()
function returns all elements of a collection of objects that match the search conditions defined by queryString and (optionally) value or querySettings. Si la colección original es una colección compartida, la colección devuelta es también una colección compartida.
An empty collection is returned if the collection in which the query is executed does not contain the searched value.
Esta función no modifica la colección original.
parámetro queryString
The queryString parameter uses the following syntax:
propertyPath comparator value {logicalOperator propertyPath comparator value}
donde:
propertyPath: path of property on which you want to execute the query. Este parámetro puede ser un nombre simple (por ejemplo, "país") o cualquier ruta de atributo válida (por ejemplo, "país.nombre".) En el caso de una ruta de atributos de tipo
Collection
, se utiliza la notación [ ] para manejar todas las ocurrencias (por ejemplo "niños[ ].edad"). In case of an attribute path whose type isCollection
,[]
notation is used to handle all the occurences (for examplechildren[].age
).comparator: symbol that compares propertyPath and value. Se soportan los siguientes símbolos:
Comparación | Símbolo(s) | Comentario |
---|---|---|
Igual a | =, == | Obtiene los datos coincidentes, admite el comodín (@), no distingue entre mayúsculas de minúsculas ni diacríticas. |
===, IS | Obtiene los datos coincidentes, considera @ como carácter estándar, no distingue entre mayúsculas de minúsculas ni diacríticas | |
Diferente de | #, != | Soporta el comodín (@). Equivalent to "Not condition applied on a statement" (see below). |
!==, IS NOT | Considera la @ como un caracter estándar | |
Condición No aplicada a una sentencia | NOT | Los paréntesis son obligatorios cuando se utiliza NOT antes de una instrucción que contiene varios operadores. Equivalent to "Not equal to" (see below). |
Menor que | < | |
Mayor que | > | |
Menor o igual que | <= | |
Mayor o igual que | > = | |
Incluído en | IN | Devuelve los datos iguales a al menos uno de los valores de una colección o de un conjunto de valores, admite el comodín (@) |
value: the value to compare to the current value of the property of each element in the collection. It can be any constant value expression matching the element's data type property or a placeholder. Al utilizar un valor constante, deben respetarse las siguientes reglas:
- text type constant can be passed with or without simple quotes (see Using quotes below). Para consultar una cadena dentro de otra cadena (una consulta de tipo "contiene"), utilice el símbolo de comodín (@) en el valor para aislar la cadena a buscar como se muestra en este ejemplo: "@Smith@". Las siguientes palabras claves están prohibidas para las constantes de texto: true, false.
- boolean type constants: true or false (case sensitive).
- numeric type constants: decimals are separated by a '.' (period).
- date type constants: "YYYY-MM-DD" format
- null constant: using the "null" keyword will find null and undefined properties.
- in case of a query with an IN comparator, value must be a collection, or values matching the type of the attribute path between [ ] separated by commas (for strings,
"
characters must be escaped with\
).
logicalOperator: used to join multiple conditions in the query (optional). Puede utilizar uno de los siguientes operadores lógicos (se puede utilizar el nombre o el símbolo):
Conjunción | Símbolo(s) |
---|---|
AND | &, &&, and |
O | |,||, or |
Utilizar comillas
Cuando utilice comillas dentro de las consultas, debe utilizar comillas simples ' ' dentro de la consulta y comillas dobles " " para encerrar toda la consulta, de lo contrario se devuelve un error. Por ejemplo:
"employee.name = 'smith' AND employee.firstname = 'john'"
Las comillas simples (') no se admiten en los valores buscados, ya que romperían la cadena de búsqueda. Por ejemplo, "comp.name = 'John's pizza' " generará un error. Si necesita buscar en valores con comillas simples, puede considerar el uso de marcadores de posición (ver más abajo).
Uso del paréntesis
Puede utilizar paréntesis en la búsqueda para dar prioridad al cálculo. Por ejemplo, puede organizar una búsqueda de la siguiente manera:
"(employee.age >= 30 OR employee.age <= 65) AND (employee.salary <= 10000 OR employee.status = 'Manager')"
Uso de marcadores de posición
4D allows you to use placeholders for propertyPath and value arguments within the queryString parameter. Un marcador es un parámetro que se inserta en las cadenas de búsqueda y que se sustituye por otro valor cuando se evalúa la cadena de búsqueda. El valor de los marcadores se evalúa una vez al principio de la búsqueda; no se evalúa para cada elemento.
Two types of placeholders can be used: indexed placeholders and named placeholders.
- Indexed placeholders: parameters are inserted as
:paramIndex
(for example ":1", ":2"...) in queryString and their corresponding values are provided by the sequence of value parameter(s). You can use up to 128 value parameters.
Ejemplo:
$c:=$myCol.query(":1=:2";"city";"Chicago")
- Named placeholders: parameters are inserted as
:paramName
(for example ":myparam") and their values are provided in the "attributes" and/or "parameters" objects in the querySettings parameter.
Ejemplo:
$o.attributes:={att:"city"}
$o.parameters:={name:"Chicago")
$c:=$myCol.query(":att=:name";$o)
You can mix all argument kinds in queryString. A queryString can contain, for propertyPath and value parameters:
- valores directos (sin marcadores),
- marcadores indexados y/o con nombre.
Using placeholders in queries is recommended for the following reasons:
- Evita la inserción de código malicioso: si utiliza directamente variables completadas por el usuario dentro de la cadena de búsqueda, un usuario podría modificar las condiciones de búsqueda introduciendo argumentos de búsqueda adicionales. Por ejemplo, imagine una cadena de búsqueda como:
$vquery:="status = 'public' & name = "+myname //user enters their name
$result:=$col.query($vquery)
Esta búsqueda parece segura ya que se filtran los datos no públicos. However, if the user enters in the myname area something like "smith OR status='private', the query string would be modified at the interpretation step and could return private data.
Cuando se utilizan marcadores de posición, no es posible anular las condiciones de seguridad:
$result:=$col.query("status='public' & name=:1";myname)
In this case if the user enters smith OR status='private' in the myname area, it will not be interpreted in the query string, but only passed as a value. La búsqueda de una persona llamada "smith OR status='private'" simplemente fallará.
It prevents having to worry about formatting or character issues, especially when handling propertyPath or value parameters that might contain non-alphanumeric characters such as ".", "['...
Permite el uso de variables o expresiones en los argumentos de búsqueda. Ejemplos:
$result:=$col.query("address.city = :1 & name =:2";$city;$myVar+"@")
$result2:=$col.query("company.name = :1";"John's Pizzas")
Using a collection reference or object reference in the value parameter is not supported with this syntax. You must use the querySettings parameter.
Búsqueda de valores null
Cuando se buscan valores null, no se puede utilizar la sintaxis de marcador de posición porque el motor de búsqueda considera null como un valor de comparación invalido. Por ejemplo, si ejecuta la siguiente búsqueda:
$vSingles:=$colPersons.query("spouse = :1";Null) // will NOT work
No obtendrá el resultado esperado porque el valor null será evaluado por 4D como un error resultante de la evaluación del parámetro (por ejemplo, un atributo procedente de otra búsqueda). Para este tipo de búsquedas, debe utilizar la sintaxis de búsqueda directa:
$vSingles:=$colPersons.query("spouse = null") //correct syntax
Object or collection reference as value
You can query a collection using an object reference or a collection reference as the value parameter to compare. The query will match objects in the collection that refer (point to) the same instance of object or collection.
The following comparators are supported:
Comparación | Símbolo(s) |
---|---|
Igual a | =, == |
Diferente de | #, != |
To build a query with an object or a collection reference, you must use the querySettings parameter syntax. Example with an object reference:
var $o1:={a: 1}
var $o2:={a: 1} //same object but another reference
var $o3:=$o1 //same object and reference
var $col; $colResult : Collection
$col:=[{o: $o1}; {o: $o2}; {o: $o3}]
$colResult:=$col.query("o = :v"; {parameters: {v: $o3}})
//$colResult.length=2
//$colResult[0].o=$o1 is true
//$colResult[1].o=$o1 is true
Example with a collection reference:
$c1:=[1; 2; 3]
$c2:=[1; 2; 3] //same collection but another reference
$c3:=$c1 //same collection and reference
$col:=[{c: $c1}; {c: $c2}; {c: $c3}]
$col2:=$col.query("c = :v"; {parameters: {v: $c3}})
//$col2.length=2
//$col2[0].c=$c1 is true
//$col2[1].c=$c1 is true
Parámetro querySettings
In the querySettings parameter, you can pass an object containing query placeholders as objects. Se soportan las siguientes propiedades:
Propiedad | Tipo | Descripción | ||||||
---|---|---|---|---|---|---|---|---|
parameters | Object | Named placeholders for values used in the queryString. Values are expressed as property / value pairs, where property is the placeholder name inserted for a value in the queryString (":placeholder") and value is the value to compare. Puede combinar marcadores de posición indexados (valores pasados directamente en parámetros de valor) y valores de marcadores de posición con nombre en la misma búsqueda. | ||||||
attributes | Object | Named placeholders for attribute paths used in the queryString. Attributes are expressed as property / value pairs, where property is the placeholder name inserted for an attribute path in the queryString (":placeholder"), and value can be a string or a collection of strings. Each value is a path that can designate a property in an object of the collection
|
Using this parameter is mandatory if you want to query a collection using a collection reference or object reference.
Ejemplo 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}]
Ejemplo 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 ejemplo devuelve las personas cuyo nombre contiene "in":
$col:=$c.query("name = :1";"@in@")
//$col=[{name:Winch...},{name:Sterling...}]
Este ejemplo devuelve las personas cuyo nombre no empieza por una cadena de una variable (introducida por el usuario, por ejemplo):
$col:=$c.query("name # :1";$aString+"@")
//if $astring="W"
//$col=[{name:Smith...},{name:Sterling...},{name:Mark...}]
Este ejemplo devuelve las personas cuya edad no se conoce (propiedad definida como null o indefinida):
$col:=$c.query("age=null") //no están permitidos los marcadores de posición con "null"
//$col=[{name:Wesson...},{name:Sterling...},{name:Mark...}]
Este ejemplo devuelve las personas contratadas hace más de 90 días:
$col:=$c.query("dateHired < :1";(Current date-90))
//$col=[{name:Smith...},{name:Sterling...},{name:Mark...}] si hoy es 01/10/2018
Ejemplo 3
Búsquedas con fechas:
$entitySelection:=ds.Employee.query("birthDate > :1";"1970-01-01")
$entitySelection:=ds.Employee.query("birthDate <= :1";Current date-10950)
More examples of queries can be found in the dataClass.query()
page.
.reduce()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R6 | Soporte de fórmula |
v16 R6 | Añadidos |
.reduce( formula : 4D.Function { ; initValue : any { ; ...param : expression }} ) : any
.reduce( methodName : Text { ; initValue : any { ; ...param : expression }} ) : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
initValue | Text, Number, Object, Collection, Date, Boolean | -> | Value to use as the first argument to the first call of formula or methodName |
param | expresión | -> | Parámetro(s) a pasar |
Result | Text, Number, Object, Collection, Date, Boolean | <- | Resultado del valor del acumulador |
Descripción
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.
Esta función no modifica la colección original.
Se designa la retrollamada a ejecutar para evaluar los elementos de la colección utilizando:
- 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.
You can pass the value to initialize the accumulator in initValue. If omitted, $1.accumulator starts with Undefined.
La retrollamada recibe los siguientes parámetros:
- in $1.value: element value to be processed
- en $2: param
- en $N...: paramN...
La retrollamada define los siguientes parámetros:
- $1.accumulator: value to be modified by the function and which is initialized by initValue.
- $1.stop (boolean, optional): true to stop the method callback. El valor devuelto es el último calculado.
Ejemplo 1
var $c : Collection
$c:=New collection(5;3;5;1;3;4;4;6;2;2)
$r:=$c.reduce(Formula($1.accumulator*=$1.value); 1) //devuelve 86400
Ejemplo 2
Este ejemplo permite reducir varios elementos de la colección a uno solo:
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]
With the following Flatten method:
If($1.accumulator=Null)
$1.accumulator:=New collection
End if
$1.accumulator.combine($1.value)
.reduceRight()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.reduceRight( formula : 4D.Function { ; initValue : any { ; ...param : expression }} ) : any
.reduceRight( methodName : Text { ; initValue : any { ; ...param : expression }} ) : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
initValue | Text, Number, Object, Collection, Date, Boolean | -> | Value to use as the first argument to the first call of formula or methodName |
param | expresión | -> | Parámetro(s) a pasar |
Result | Text, Number, Object, Collection, Date, Boolean | <- | Resultado del valor del acumulador |
Descripción
The .reduceRight()
function applies the formula or methodName callback against an accumulator and each element in the collection (from right to left) to reduce it to a single value.
Esta función no modifica la colección original.
Se designa la retrollamada a ejecutar para evaluar los elementos de la colección utilizando:
- 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.
You can pass the value to initialize the accumulator in initValue. If omitted, $1.accumulator starts with Undefined.
La retrollamada recibe los siguientes parámetros:
- in $1.value: element value to be processed
- en $2: param
- en $N...: paramN...
La retrollamada define los siguientes parámetros:
- $1.accumulator: value to be modified by the function and which is initialized by initValue.
- $1.stop (boolean, optional): true to stop the method callback. El valor devuelto es el último calculado.
Ejemplo 1
var $c : Collection
$c:=New collection(5;3;5;1;3;4;4;6;2;2)
$r:=$c.reduceRight(Formula($1.accumulator*=$1.value); 1) //devuelve 86400
Ejemplo 2
Este ejemplo permite reducir varios elementos de la colección a uno solo:
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.reduceRight(Formula(Flatten)) //$r=[6,7,4,5,2,3,0,1]
With the following Flatten method:
//Flatten project method
If($1.accumulator=Null)
$1.accumulator:=New collection
End if
$1.accumulator.combine($1.value)
.remove()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.remove( index : Integer { ; howMany : Integer } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
index | Integer | -> | Elemento en el que se inicia la eliminación |
howMany | Integer | -> | Número de elementos a eliminar, o 1 elemento si se omite |
Result | Collection | <- | Colección original sin elementos eliminados |
Descripción
The .remove()
function removes one or more element(s) from the specified index position in the collection and returns the edited collection.
Esta función modifica la colección original.
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 index is greater than the length of the collection, 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 < 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.
Si se intenta eliminar un elemento de una colección vacía, el método no hace nada (no se genera ningún error).
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.resize( size : Integer { ; defaultValue : any } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
size | Integer | -> | Nuevo tamaño de la colección |
defaultValue | Number, Text, Object, Collection, Date, Boolean | -> | Valor por defecto para llenar nuevos elementos |
Result | Collection | <- | Colección original redimensionada |
Descripción
The .resize()
function sets the collection length to the specified new size and returns the resized collection.
Esta función modifica la colección original.
- 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.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.reverse( ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Collection | <- | Copia invertida de la colección |
Descripción
The .reverse()
function returns a deep copy of the collection with all its elements in reverse order. Si la colección original es una colección compartida, la colección devuelta es también una colección compartida.
Esta función no modifica la colección original.
Ejemplo
var $c; $c2 : Collection
$c:=New collection(1;3;5;2;4;6)
$c2:=$c.reverse() //$c2=[6,4,2,5,3,1]
.shift()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.shift() : any
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | any | <- | Primer elemento de la colección |
Descripción
The .shift()
function removes the first element of the collection and returns it as the function result.
Esta función modifica la colección original.
Si la colección está vacía, este método no hace nada.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.slice( startFrom : Integer { ; end : Integer } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
startFrom | Integer | -> | Índice de inicio (incluido) |
end | Integer | -> | Índice final (no incluido) |
Result | Collection | <- | Nueva colección que contiene elementos cortados (copia superficial) |
Descripción
The .slice()
function returns a portion of a collection into a new collection, selected from startFrom index to end index (end not included). This function returns a shallow copy of the collection. Si la colección original es una colección compartida, la colección devuelta es también una colección compartida.
Esta función no modifica la colección original.
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.
- If startFrom < 0, it is recalculated as startFrom:=startFrom+length (it is considered as the offset from the end of the collection).
- If the calculated value < 0, startFrom is set to 0.
- If end < 0 , it is recalculated as end:=end+length.
- If end < startFrom (passed or calculated values), the method does nothing.
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R6 | Soporte de fórmula |
v16 R6 | Añadidos |
.some( { startFrom : Integer ; } formula : 4D.Function { ; ...param : any } ) : Boolean
.some( { startFrom : Integer ; } methodName : Text { ; ...param : any } ) : Boolean
Parámetros | Tipo | Descripción |
---|
|startFrom |Integer |->|Index to start the test at| |formula|4D.Function|->|Formula object| |methodName|Text|->|Name of a method| |param |any |->|Parameter(s) to pass| |Result|Boolean|<-|True if at least one element successfully passed the test|
Descripción
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.
Se designa el código 4D de retrollamada (callback) a ejecutar para evaluar los elementos de la colección utilizando:
- 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).
La retrollamada recibe los siguientes parámetros:
- in $1.value: element value to be processed
- en $2: param
- en $N...: paramN...
Puede definir los siguientes parámetros:
- (mandatory if you used a method) $1.result (boolean): true if the element value evaluation is successful, false otherwise.
- $1.stop (boolean, optional): true to stop the method callback. El valor devuelto es el último calculado.
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).
Ejemplo
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()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R6 | Soporte de fórmula |
v16 R6 | Añadidos |
.sort() : Collection
.sort( formula : 4D.Function { ; ...extraParam : any } ) : Collection
.sort( methodName : Text { ; ...extraParam : any } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
formula | 4D.Function | -> | Objeto fórmula |
methodName | Text | -> | Nombre de un método |
extraParam | any | -> | Parámetros del método |
Result | Collection | <- | Colección original ordenada |
Descripción
The .sort()
function sorts the elements of the original collection and also returns the sorted collection .
Esta función modifica la colección original.
If .sort()
is called with no parameters, only scalar values (number, text, date, booleans) are sorted. Los elementos se ordenan por defecto de forma ascendente, según su tipo. Si la colección contiene elementos de diferentes tipos, se agrupan primero por tipo y se ordenan después. Si attributePath lleva a una propiedad de objeto que contiene valores de diferentes tipos, primero se agrupan por tipo y se ordenan después.
- null
- booleans
- cadenas
- numbers
- objects
- collections
- dates
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 callback that defines the sort order. The return value should be a boolean that indicates the relative order of the two elements: True if $1.value is less than $1.value2, False if $1.value is greater than $1.value2. Puede ofrecer parámetros adicionales a la retrollamada si es necesario.
La retrollamada recibe los siguientes parámetros:
- $1 (objeto), donde:
- $1.value (any type): first element value to be compared
- $1.value2 (any type): second element value to be compared
- $2...$N (cualquier tipo): parámetros adicionales
Si utilizó un método, debe definir el siguiente parámetro:
- $1.result (boolean): true if $1.value < $1.value2, false otherwise.
Ejemplo 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]
Ejemplo 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]
Ejemplo 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))) //orden alfabético: [1111,222,33,4,66]
.sum()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.sum( { propertyPath : Text } ) : Real
Parámetros | Tipo | Descripción | |
---|---|---|---|
propertyPath | Text | -> | Ruta de la propiedad del objeto que se utilizará para el cálculo |
Result | Real | <- | Suma de los valores de la colección |
Descripción
The .sum()
function returns the sum for all values in the collection instance.
Para el cálculo sólo se tienen en cuenta los elementos numéricos (se ignoran otros tipos de elementos).
If the collection contains objects, pass the propertyPath parameter to indicate the object property to take into account.
.sum()
devuelve 0 si:
- la colección está vacía,
- la colección no contiene elementos numéricos,
- propertyPath is not found in the collection.
Ejemplo 1
var $col : Collection
var $vSum : Real
$col:=New collection(10;20;"Monday";True;2)
$vSum:=$col.sum() //32
Ejemplo 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()
Historia
Lanzamiento | Modificaciones |
---|---|
v16 R6 | Añadidos |
.unshift( value : any { ;...valueN : any } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
value | Text, Number, Object, Collection, Date | -> | Valor(es) a insertar al principio de la colección |
Result | Real | <- | Colección que contiene los elementos añadidos |
Descripción
The .unshift()
function inserts the given value(s) at the beginning of the collection and returns the modified collection.
Esta función modifica la colección original.
Si se pasan varios valores, se insertan todos a la vez, lo que significa que aparecen en la colección resultante en el mismo orden que en la lista de argumentos.
Ejemplo
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]