How can I limit the number of results returned by an expensive filter expression in AppleScript?
-
31-05-2021 - |
Domanda
In my Apple Notes automation on macOS Big Sur, I’d like to load any 5 notes whose name contains a substring. For example, if I know that I actually have 5 notes that match the query, I can write something like this:
tell application "Notes"
set matches to id of (notes 1 thru 5 in default account whose name contains "a")
end tell
This runs relatively fast (< 1 second on my account with thousands of notes), because it terminates as soon as it finds those 5 matches and doesn’t look any further. For comparison, a query without such "1 thru 5" clause (or a count query) times out before it even returns any results, which is understandable. However, my problem is that if there aren’t enough (i.e., fewer than 5) matches, the query will error without returning any results:
Notes got an error: Can’t get notes 1 thru 5 of default account whose name contains "a". Invalid index.
Thus, my question is whether there’s a way for me to get "at most 5 results" in a single query?
Soluzione
Thus, my question is whether there’s a way for me to get "at most 5 results" in a single query?
No, it cannot be done in a single query.
If you want to loop through a given count downwards then the following example AppleScript code is how I'd do it:
set maxNumber to 5
set searchString to "a"
set matches to missing value
repeat with i from maxNumber to 1 by -1
if matches is equal to missing value then
try
tell application "Notes"
set matches to id of ¬
(notes 1 thru i in default account ¬
whose name contains searchString)
end tell
end try
if matches is not equal to missing value then exit repeat
end if
end repeat
return matches