For Each (Map, Reduce) and assignment: Is it possible to loop over a collection (e.g. lines in the clipboard) and retrieve the changed collection?

In my normal coding environment (PHP) I would do something like this:

$str = "foo bar baz";
echo $str . "\n"; // "foo bar baz\n"
$arr = explode(' ', $str);
$arr = array_map(fn($elem) => strtoupper($elem), $arr);
$str = implode(' ', $arr);
echo $str . "\n"; // "FOO BAR BAZ\n"

or even

$str = "foo bar baz";
echo $str . "\n"; // "foo bar baz\n"
$str = array_reduce(
  explode(' ', $str),
  fn($carry, $item) => $carry ? $carry . " " . strtoupper($item) : strtoupper($item),
  ''
);
echo $str . "\n"; // "FOO BAR BAZ\n"

If we don't get too fancy this basically does the following:

  • loop over a collection and do something to every element of the collection
  • assign the result of your work to the collection's item we're currently iterating over
  • return the changed collection

I know KM has a for each action, but I can't seem to figure out how to do the same thing I did here: There is "lines in collection" or "substrings in collection" and I can let KM do some work on each of the elements, but how do I assign the result? And how do I return the changed collection?

Come to think of it: The nearest approximation of what I want would look like this in PHP:

$str = "foo bar baz";
echo $str . "\n";
$arr = explode(' ', $str);
foreach($arr as $key => $elem) {
  $arr[$key] = strtoupper($elem);
}
$str = implode(' ', $arr);
echo $str . "\n";

I know how I could help myself in multiple ways (like running a script action), but can you do it with KM native tools?

You could have Keyboard Maestro do something with each line (in this example multiply by 2) and append these results one at a time to a new Variable.

EXAMPLE Lines.kmmacros (3.6 KB)

2 Likes

and of course, if you are used to writing some code, you have the Execute JavaScript for Automation action, with:

  • the usual .map .reduce .flatMap etc array methods, and
  • the Keyboard Maestro Engine .getvariable and .setvariable methods

but perhaps the most direct form of native mapping in Keyboard Maestro is slightly hidden behind what it calls the Filter action, which sounds like a way of defining subsets, but actually provides a rich set of prebuilt Filter X with Y to Z mappings, applicable to the lines of a string.

2 Likes