Hi,
I write simple script for parsing txt files.
This is input string: {“item1”, “item2”, “item3”, “item4”, “item5”, “item6”, “item7”, “item8”…}
How to get this output string: {{“item1”, “item2”, “item3”, “item4”}, {“item5”, “item6”, “item7”, “item8”}…}?
on splitList(n, someList)
set output to {}
repeat with i from 1 to (count someList) by n
try
set end of output to items i thru (i + n - 1) of someList
on error
set end of output to items i thru -1 of someList
end try
end repeat
return output
end splitList
-- Example
splitList(4, {"item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9"})
I understand the reason for the on error, which is incase the split number (in this case 4) is a number greater than the number of items.
Can you explain the reason for the repeat loop , in you script I do not understand it’s inclusion and what the BY part is for?.
If I used the below script would there be a difference? I fear I am missing something obvious, so please forgive me if my question seems dumb. :rolleyes:
splitList(4, {"item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9"})
on splitList(n, someList)
try
set output to {items 1 thru n of someList}
set end of output to items (1 + n) thru -1 of someList
on error
set output to {items 1 thru -1 of someList}
end try
return output
end splitList