Recursive Shortcut

Just for learning purposes, I wrote a shortcut that calls a recursive shortcut that returns the factorial of a number. The learning part for me was the recursion.

The calling shortcut:

Get Factorial.shortcut (22.1 KB)

The called shortcut:

Factorial.shortcut (22.2 KB)

I wanted an example of a recursive handler that manipulated text, and Google AI provided the following:

set theText to "macOS"
set reversedText to reverseText(theText)

on reverseText(theText)
	if (length of theText) ≤ 1 then
		return theText
	else
		return (last character of theText) & my reverseText(text 1 thru -2 of theText)
	end if
end reverseText

The calling shortcut of the shortcut equivalent is:

Get Reversed Text.shortcut (22.2 KB)

The called shortcut of the shortcut equivalent is:

Reverse Text.shortcut (22.9 KB)

Continuing on with my learning, I wanted to write a shortcut that recursively gets all folders in a source folder. The following worked but is abysmally slow with even a moderately-sized folder. I don’t know if that’s a result of the repeat loop that removes files or if there’s some error in the recursion.

Get Folders.shortcut (21.7 KB)

Find Folders.shortcut (22.6 KB)

Repeat and Repeat with Each actions do not provide an exit repeat marker. If the desired task can be performed at the very beginning of the shortcut, recursion can be used. In the following example, the user is prompted to enter a person’s name and continues with the remainder of the shortcut when the user enters the word none or None.

Dialog Recurse.shortcut (22.3 KB)

I finally got the above-noted shortcut to work correctly. A few comments:

  • The shortcut is called by another shortcut.

  • Folder objects are returned, but this is easily changed to return folder paths.

  • Moving the first Add to Variable action up two places will cause the shortcut to return both folders and files.

  • The timing result with a smallish folder was 220 milliseconds but can be several seconds if the source folder is large.

  • The Shortcuts app does not have the native ability to recursively get folders alone or both folders and files.

Get Folders.shortcut (22.6 KB)