Hello!
I’m trying to write a subroutine that will rearrange the order of a list, that is: move one item in the list to a different location in the same list (I can’t believe Applescript don’t have an easy way to do this!). The code below works, but only if you move the selected item to a previous position in the list:
my rearrange_list({“one”, “two”, “three”, “four”, “five”, “six”}, 3, “four”)
→ {“one”, “two”, “four”, “three”, “five”, “six”} = OK
The problem: if I try to move the same item to a later position its inserted one step to early:
my rearrange_list({“one”, “two”, “three”, “four”, “five”, “six”}, 6, “four”)
→ {“one”, “two”, “three”, “five”, “four”, “six”} = Not OK
I suppose this is quite easy to fix, but so far I haven’t been able to figure out how exactly. Any suggestions would be much appreciated. Thank you.
my rearrange_list({"one", "two", "three", "four", "five", "six"}, 2, "four")
on rearrange_list(a_list, item_index, replacement_item)
set selected_item to item item_index of a_list
if selected_item is not replacement_item then
set temp to {}
repeat until a_list is {}
set this_item to item 1 of a_list
if this_item is not replacement_item then
if this_item is selected_item then
set a_list to {""} & a_list
set end of temp to replacement_item
repeat with i in (rest of a_list)
set i to i as string
if i is not replacement_item then
set end of temp to i
end if
end repeat
exit repeat
else
set end of temp to this_item
end if
end if
set a_list to rest of a_list
end repeat
copy temp to a_list
end if
return a_list
end rearrange_list