Skip to content

Instantly share code, notes, and snippets.

@scriptingstudio
Created February 10, 2025 18:25
Show Gist options
  • Select an option

  • Save scriptingstudio/95e8ad1f312ae47ecd810b526b31de0e to your computer and use it in GitHub Desktop.

Select an option

Save scriptingstudio/95e8ad1f312ae47ecd810b526b31de0e to your computer and use it in GitHub Desktop.
Array transformation function
<#
Inspired by Doug Finke's map function
https://dfinke.github.io/search%20engines/2024/11/13/Introducing-a-Custom-map-Function-in-PowerShell-for-Functional-Programming.html
#>
function Convert-Object {
[CmdletBinding()]
[alias('map')]
param (
[Parameter(Mandatory)]
$func,
[Parameter(ValueFromRemainingArguments,Mandatory)]
$arrays,
[alias('full')][switch]$max
)
$dataType = $arrays.GetType().Name
if ($dataType -eq 'Object[]') {
# If arrays are simple objects, apply the function directly
$arrays | ForEach-Object {& $func $_}
}
elseif ($dataType -eq 'List`1') {
# If arrays are lists, process them in parallel
$arrayCount = $arrays.Count
# Calculate output dimension
$count = if ($max) {
($arrays | ForEach-Object {$_.count} | Measure-Object -Maximum).Maximum
} else {
($arrays | ForEach-Object {if ($_.count) {$_.count}} | Measure-Object -Minimum).Minimum
}
# Get the parameter names of the function
$funcParams = if ($func -is [scriptblock]) {
$func.Ast.ParamBlock.Parameters |
ForEach-Object {$_.Name.VariablePath.UserPath}
} else {
(Get-Command $func).Parameters.Keys -as [array]
}
# Iterate over each index and apply the function
for ($i = 0; $i -lt $count; $i++) {
$funcSplat = [ordered]@{}
for ($ac = 0; $ac -lt $arrayCount; $ac++) {
if ($arrays[$ac] -ne $null) {
$funcSplat["$($funcParams[$ac])"] = $arrays[$ac][$i]
}
}
& $func @funcSplat
}
}
} # END Convert-Object
$who = 'John', 'Jane' , 'Doe', 'Smith'
$age = 20, 30, 40 , 50,500,77
$where = 'New York', 'California', 'Texas', 'Florida' ,'Hiranyaloka'
map {
param($who, $age, $where)
[PSCustomObject][Ordered]@{
Name = $who
Age = $age
Location = $where
}
} $who $age $where -max
Name Age Location
---- --- --------
John 20 New York
Jane 30 California
Doe 40 Texas
Smith 50 Florida
500 Hiranyaloka
77
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment