[TIP] Moving elements of a collection

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

[TIP] Moving elements of a collection

4D Tech mailing list
Collections are not arrays. So is I have a collection based listbox and
want to have a control to allow the user to move a selected element within
the collection how do I do that?

One way would be to allow her to drag and drop the element to the new
position. The other way is a spinner of some sort to allow moving a
selected element up or down. In both cases I need to actually move the
element within the collection.

Here is a method I came up with. It takes a collection, the selected
element index and a 'direction'. This is simply the number of places to
move the selected element. Positive moves it 'up' the list and negative
'down'. I did not follow 4D's approach to these sorts of things and wrap
the movement. In my method if the collection won't support the requested
move nothing happens.

Contents of the collection don't matter.

*C_COLLECTION*($col)

$col:=*New collection*("a";"b";"c";"d")

*Collection_move* ($col;0;3)  //$col=["b","c","d";"a"]

*Collection_move* ($col;3;-3)  //$col=["a";"b","c","d"]


$col:=*New collection*(\

*New object*("key";"a");\

*New object*("key";"b");\

*New object*("key";"c");\

*New object*("key";"d"))


*Collection_move* ($col;0;3) //  [{key:b},{key:c},{key:d},{key:a}]


And here's the method:

  //  Collection_move (col; long; long)

  // $1: collection

  // $2: element to move

  // $3: direction and magnitude

  // Written by: Kirk as Designer

  // ------------------

  // Purpose: moves an element of collection

  // if $3 > 0 the element is moved 'up'


*C_COLLECTION*(*$1*)

*C_LONGINT*(*$2*;$i)

*C_LONGINT*(*$3*;$direction;$x)


$i:=*$2*

$direction:=*$3*


$x:=$i+$direction  //  proposed new location


*Case of*

*:* (*$1*=*Null*)

*:* (*$1*.length=0)

*:* ($direction=0)

*:* ($i<0) | ($i>(*$1*.length-1))

*:* ($x<0) | ($x>(*$1*.length-1))

*:* ($direction>0)  //  moving up

*$1*.*insert*($x+1;*$1*[$i])

*$1*.*remove*($i)


*Else*   // moving down

*$1*.*insert*($x;*$1*[$i])

*$1*.*remove*($i+1)


*End case*


--
Kirk Brooks
San Francisco, CA
=======================

What can be said, can be said clearly,
and what you can’t say, you should shut up about

*Wittgenstein and the Computer *
**********************************************************************
4D Internet Users Group (4D iNUG)
Archive:  http://lists.4d.com/archives.html
Options: https://lists.4d.com/mailman/options/4d_tech
Unsub:  mailto:[hidden email]
**********************************************************************