Search code examples
loopsfor-loopapplescript

Repeat loop with if conditions for first and last time


I have a script that I made that works fine but I have to make some very minor edits to the output. Instead I'd like to just do it correctly.

on run {input, parameters}
set the formatted to {}
set listContents to get the clipboard
set delimitedList to paragraphs of listContents
repeat with listitem in delimitedList
    set myVar to "@\"" & listitem & "\"," & (ASCII character 10)
    copy myVar to the end of formatted
end repeat
display dialog formatted as string
return formatted as string
end run

I'd like prepend the first item slightly differently and append the last a little different.

I tried the following but the script is not right.

repeat with n from 1 to count of delimitedList
  -- not sure how to if/else n == 0 or delimitedList.count
end repeat

Solution

  • There is a more efficient way, text item delimiters. It can insert the comma and the linefeed character between the list items

    on run {input, parameters}
        set the formatted to {}
        set listContents to get the clipboard
        set delimitedList to paragraphs of listContents
        repeat with listitem in delimitedList
            copy "@" & quote & listitem & quote to the end of formatted
        end repeat
        set {saveTID, text item delimiters} to {text item delimiters, {"," & linefeed}}
        set formatted to formatted as text
        set text item delimiters to saveTID
        display dialog formatted
        return formatted
    end run
    

    Side note: ASCII character 10 is deprecated since macOS 10.5 Leopard, there is linefeed, tab (9), return (13), space (32) and quote (34).