Menu
Raith's website

Pattern: "Functional String Building"

javascript powershell software

I don’t do functional programming as a rule. Maybe I should. As it is I merely flirt with it now and then.

Here is one pattern that I have definitely settled on, and that I think everyone should use. Functional string building. When you finish reading this there should be no excuse for ugly old imperative concatenation loops.

Instead we create our concatenated mega-string using the nice functional approach of mapping our input list inside a multi-line template literal.

JavaScript  [try it online]

let list = ["Apple", "Banana", "Cherry"];  
let freshness = fruit => `I like a nice fresh ${fruit}`;  
let poem = `Fruity Freshness  
---------------- 
${list.map(freshness).join('\n')} I'm full`;

PowerShell  [try it online]

$list = "Apple", "Banana", "Cherry" 
function freshness ([Parameter(ValueFromPipeline)]$fruit) {Process{ "I like a nice fresh $fruit" }} 
$poem = @" 
Fruity Freshness 
---------------- 
$(($list | freshness) -join "`n") 
I'm full 
"@

C#  [try it online]

using System.Linq;
var list = new System.Collections.Generic.List<string> {"Apple", "Banana", "Cherry"}; 
Func<string,string> freshness = (fruit) => $"I like a nice fresh {fruit}"; 
var poem = $"Fruity Freshness 
---------------- 
{String.Join("\n", list.Select(freshness).ToList())} 
I'm full";

All return the same result:

Fruity Freshness 
---------------- 
I like a nice fresh Apple 
I like a nice fresh Banana 
I like a nice fresh Cherry 
I'm full


I used a function statement in PowerShell because piping to it is more natural. You can instead assign a scriptblock to a variable and make it more analogous to the other examples. Notice that you now have to &execute the $variable in the pipeline.

PowerShell modifications  [try it online]

$freshness = {Param([Parameter(ValueFromPipeline)]$fruit) Process{ "I like a nice fresh $fruit" }} $list | &$freshness