Merger

Merger script that joins hashtables.

Kod

#!/usr/bin/env pwsh

function AryMerge($aobj, $asource) {
    if ($aobj.Length -eq 0)    { return $asource }
    if ($asource.Length -eq 0) { return $aobj    }
    $to_add = @()
    foreach ($e in $asource) {
        if (-not $aobj.Contains($e)) {
            $to_add += $e
        }
    }
    return ($aobj + $to_add)
}

function HashMergeInto($obj, $source) {
    if ((-not $obj) -and $source) { return $source }
    foreach ($k in $source.keys) {
        $v_src = $source[$k]
        if (-not $obj.ContainsKey($k)) { $obj.Add($k, $v_src); continue; }
        $v_dst = $obj[$k]
        if ($v_src -is [Hashtable] -and $v_dst -is [Hashtable]) { HashMergeInto $v_dst $v_src | Out-Null   ; continue; }
        if ($v_src -is [Array]     -and $v_dst -is [Array])     { $obj[$k] = (AryMerge $v_dst $v_src) ; continue; }
    }
    return $obj
}

$a = @{ "hasz" = @{"a" = "b"}; "arik" = @(1,2,3,4,5,6,7,8) }
$b = @{ "e" = "f"; "hasz" = @{ "x" = "y"; "a" = "c" }; "arik" = @(1,2,3,4,5,6,7,8,8) }

(HashMergeInto $a $b) | ConvertTo-JSON | Write-Output
#!/usr/bin/env pwsh function AryMerge($aobj, $asource) { if ($aobj.Length -eq 0) { return $asource } if ($asource.Length -eq 0) { return $aobj } $to_add = @() foreach ($e in $asource) { if (-not $aobj.Contains($e)) { $to_add += $e } } return ($aobj + $to_add) } function HashMergeInto($obj, $source) { if ((-not $obj) -and $source) { return $source } foreach ($k in $source.keys) { $v_src = $source[$k] if (-not $obj.ContainsKey($k)) { $obj.Add($k, $v_src); continue; } $v_dst = $obj[$k] if ($v_src -is [Hashtable] -and $v_dst -is [Hashtable]) { HashMergeInto $v_dst $v_src | Out-Null ; continue; } if ($v_src -is [Array] -and $v_dst -is [Array]) { $obj[$k] = (AryMerge $v_dst $v_src) ; continue; } } return $obj } $a = @{ "hasz" = @{"a" = "b"}; "arik" = @(1,2,3,4,5,6,7,8) } $b = @{ "e" = "f"; "hasz" = @{ "x" = "y"; "a" = "c" }; "arik" = @(1,2,3,4,5,6,7,8,8) } (HashMergeInto $a $b) | ConvertTo-JSON | Write-Output
Jesteś w sekcji

comments powered by Disqus