Created
November 22, 2024 17:27
-
-
Save lamg/66f2da3a2127a74a0dfce401e0707109 to your computer and use it in GitHub Desktop.
Compare objects .Net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#r "nuget: ObjectDumper.NET, 4.3.4-pre" | |
let greenFragment x = | |
let ansiGreen = "\x1b[32m" | |
let ansiReset = "\x1b[0m" | |
$"%s{ansiGreen}%s{x}%s{ansiReset}" | |
let redFragment x = | |
let ansiRed = "\x1b[31m" | |
let ansiReset = "\x1b[0m" | |
$"%s{ansiRed}%s{x}%s{ansiReset}" | |
let fillArrays (xs: string array) (ys: string array) = | |
let diff = xs.Length - ys.Length | |
if diff > 0 then | |
xs, Array.replicate diff "" |> Array.append ys | |
else | |
Array.replicate (diff * -1) "" |> Array.append xs, ys | |
let diffSideBySide (actual: string array) (expected: string array) = | |
let max = actual |> Array.maxBy _.Length |> _.Length | |
let fillLine (x: string) = | |
let diff = max - x.Length | |
let fill = if diff > 0 then String.replicate diff " " else "" | |
$"{x}{fill}" | |
fillArrays actual expected | |
|> fun (xs, ys) -> Array.zip xs ys | |
|> Array.map (function | |
| (x, y) when x <> y -> $"{redFragment (fillLine x)} {greenFragment y}" | |
| (x, y) -> $"{fillLine x} {y}") | |
let diffObjects (actual: 'a) (expected: 'b) = | |
let left = ObjectDumper.Dump actual |> _.Split('\n') | |
let right = ObjectDumper.Dump expected |> _.Split('\n') | |
diffSideBySide left right | |
type Dog = | |
{ name: string | |
color: string | |
address: string } | |
let morty = | |
{ name = "morty" | |
color = "green" | |
address = "Pennsylvania Avenue 1600" } | |
let rick = | |
{ name = "rick" | |
color = "rick" | |
address = morty.address } | |
diffObjects morty rick |> Array.iter System.Console.WriteLine |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment