Home > Mobile >  Repeat loop with if conditions for first and last time
Repeat loop with if conditions for first and last time

Time:01-14

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

CodePudding user response:

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).

CodePudding user response:

In addition to an index or range, the various items of a list can also be accessed by using location parameters such as first, last, beginning, etc (note that AppleScript lists start at index 1). To deal with the first and last items separately, you can do something like:

on run {input, parameters} -- example
   set formatted to {}
   set delimitedList to paragraphs of (the clipboard)
   if delimitedList is not {} then
      if (count delimitedList) > 2 then repeat with anItem in items 2 thru -2 of delimitedList
         set the end of formatted to "@" & quote & anItem & quote
      end repeat
      set the beginning of formatted to "@" & quote & "First: " & first item of delimitedList & quote -- or whatever
      if rest of delimitedList is not {} then set the end of formatted to "@" & quote & "Last: " & last item of delimitedList & quote -- or whatever
      set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "," & linefeed}
      set {formatted, AppleScript's text item delimiters} to {formatted as text, tempTID}
   end if
   display dialog formatted as text
   return formatted as text
end run
  • Related