Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Offset in list



Bastiaan Boertien wrote on Fri, 11 Feb 2005 13:54:41 +0100:

>Hi List
>
>Is there a way to get the offset of an item from a list as number
>
>because we can do it with a string like this
>set theString to "658947123"
>
>offset of "4" in theString
>
>I know how to do it with a repeat but that's to slow

It depends what's in the list. If it's just integers and the one you want 
is likely to be in the first 40 or so, a repeat compares quite favourably 
with anything else for speed.

  on getIndex(theItem, theList)
    script o
      property l : theList
    end script

    if theList contains {theItem} then
      set i to 1
      repeat until (item i of o's l is theItem)
        set i to i + 1
      end repeat
    else
      set i to 0
    end if

    return i
  end getIndex

This is also a safe option if the list contains items that can't be 
coerced to string or which might cause confusion if they were.

Otherwise, there's this slightly faster version of the handler jj posted 
earlier:

  on IndexOfItem(theItem, theList)
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to return
    set theList to {"", theList, ""} as string
    set AppleScript's text item delimiters to {"", theItem, ""} as string
    set i to (count paragraphs of text item 1 of theList) mod (count 
paragraphs of theList)
    set AppleScript's text item delimiters to astid

    return i
  end IndexOfItem


NG
 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Applescript-users mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/applescript-users/email@hidden

This email sent to email@hidden



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.