KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: A method to copy elements with the same collection
PRODUCT: 4D | VERSION: 17 | PLATFORM: Mac & Win
Published On: April 18, 2019
Your current browser may not allow you to download the asset. We recommend Mozilla Firefox or Google Chrome.
Log In

4D V17 offers a rich selection of collection methods to add and remove element to and from collections. Developers can also use concat() and reduce() to add/remove multiple elements at one time. However, it does not yet offer a member method to move element(s) inside the same collection.
Below is a method used to copy any number of elements of a collection to a target location within the same collection. The copied elements will replace elements at target locations. The size of collection is not modified.

// Name: Collection_CopyWithIn
// Description: Method will return a collection in which a part of collection is copied
// to another location of the same acollection without changing its size
// Parameters:
// $1 (Collection) - target collection
// $2 (Longint)- Zero based index to copy elements to (included)
// $3 (Longint)- Zero based index to start copying elements from (included)
// $4 (Longint)- Zero based index to end copying elements from (not included)
//
// Return
// $0(Collection)- a modified collection with copied elements

C_COLLECTION($0;$1;$tempCollection)
C_LONGINT($2;$3;$4;$numberOfEleToCopy)

//If target is bigger than collection length, nothing is copied
If ($2>=$1.length)
  $0:=$1
End if
//If start is smaller than 0 then add it to length of collection
While ($2<0)
  $2:=$2+$1.length
End while
//Get the elements to copy from
$tempCollection:=$1.slice($3;$4)
//Calculate the start and end to copy to
If($tempCollection.length > ($1.length - $2))
  $numberOfEleToCopy:=$1.length-$2
  $tempCollection:=$tempCollection.slice(0;$numberOfEleToCopy)
Else
  $numberOfEleToCopy:=$tempCollection.length
End if
//Remove original elements and copy new elements in
$0:=($1.remove($2;$numberOfEleToCopy)).combine($tempCollection;$2)



This method is useful to move elements around in a collection. Instead of creating a temporary collection, or split current collection and concat them, this CopyWithIn method offers an easy way to move elements. The copying process is performed at high performance because it does not involve iterating through the collection


Below is an example:

C_COLLECTION($c:)
$c:=New collection(1;2;3;4;5)

$c::=Collection_CopyWithIn ($c;0;3;4) //[4,2,3,4,5]

$c::=Collection_CopyWithIn($c;-2; -3; -1) //[1,2,3,3,4]

$c::=Collection_CopyWithIn ($c;-2;0;$c.length)//[1, 2, 3, 1, 2]

$c::=Collection_CopyWithIn ($c;0;2;$c.length)//[3, 4, 5, 4, 5]