if I have a script which generates lists which sometimes contain 1,2,3, or 4 items…
How is the best way to add an item in between items 1 and 2?-- Pushing everything that was in 2-4 now to 3-5? But yet if the list only has 1 item, it just creates a 2nd item?
property _Loader : run application "LoaderServer"
----------------------------------------------------------------------
-- DEPENDENCIES
property _List : missing value
on __load__(loader)
set _List to loader's loadLib("List")
end __load__
----------------------------------------------------------------------
__load__(_Loader's makeLoader())
set lst to {1, 2, 3, 4}
set lst to _List's insertItem(lst, "x", 1)
lst --> {1, "x", 2, 3, 4}
If you’ve not used AppleMods’ libraries before, you’ll need to download and install AppleMods’ Loader system first. Run the Loader installer, then download the List library and add it to the ASLibraries folder. You can use the LoaderWizard applet to generate the library loading code to paste at the top of your script.
set lisst to {1, 2, 3, 4, 5, 6, 7, 8, 9}
return addtolist(lisst, 6, "i")
on addtolist(thelist, placetoinsert, whattoinsert)
set tot to count of items of thelist
if placetoinsert is less than 1 then set placetoinsert to 1
if placetoinsert is greater than tot then
set end of thelist to whattoinsert
set NL to thelist
else
set n to placetoinsert
if placetoinsert is 1 then
set lis1 to {whattoinsert}
else
set lis1 to {}
repeat with i from 1 to n - 1
set end of lis1 to item i of thelist
end repeat
set end of lis1 to whattoinsert
end if
repeat with i from n to number of items in thelist
set end of lis1 to item i of thelist
end repeat
set NL to lis1
end if
return NL
end addtolist
on addAtPosition(thelist, theItem, indexPosition)
set listCount to count of thelist
if indexPosition is greater than listCount or indexPosition is -1 then
thelist & theItem
else if indexPosition is less than -listCount or indexPosition is 1 then
{theItem} & thelist
else if indexPosition is greater than 1 then
items 1 thru (indexPosition - 1) of thelist & theItem & items indexPosition thru listCount of thelist
else if indexPosition is less than -1 then
items 1 thru indexPosition of thelist & theItem & items (indexPosition + 1) thru listCount of thelist
else
thelist
end if
end addAtPosition
set thelist to {1, 2, 3, 4, 5, 6, 7, 8, 9}
addAtPosition(thelist, "i", 6)
--> {1, 2, 3, 4, 5, "i", 6, 7, 8, 9}
addAtPosition(thelist, "i", -5)
--> {1, 2, 3, 4, 5, "i", 6, 7, 8, 9}