|
1 | 1 | package sliceutil |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "strings" |
4 | 5 | "testing" |
5 | 6 |
|
6 | 7 | osutils "github.com/projectdiscovery/utils/os" |
@@ -308,3 +309,76 @@ func TestVisitRandomZero(t *testing.T) { |
308 | 309 | } |
309 | 310 | require.True(t, timesDifferent > 0) |
310 | 311 | } |
| 312 | + |
| 313 | +func TestDedupeFunc(t *testing.T) { |
| 314 | + t.Run("basic-string-deduplication", func(t *testing.T) { |
| 315 | + input := []string{"hello", "HELLO", "world", "WORLD"} |
| 316 | + result := DedupeFunc(input, func(s string) any { return strings.ToLower(s) }) |
| 317 | + require.Equal(t, []string{"hello", "world"}, result) |
| 318 | + }) |
| 319 | + |
| 320 | + t.Run("struct-deduplication", func(t *testing.T) { |
| 321 | + type Person struct { |
| 322 | + ID int |
| 323 | + Name string |
| 324 | + } |
| 325 | + input := []Person{ |
| 326 | + {ID: 1, Name: "Alice"}, |
| 327 | + {ID: 2, Name: "Bob"}, |
| 328 | + {ID: 1, Name: "Alice Different"}, // Same ID, different name |
| 329 | + {ID: 3, Name: "Charlie"}, |
| 330 | + } |
| 331 | + result := DedupeFunc(input, func(p Person) any { |
| 332 | + return p.ID |
| 333 | + }) |
| 334 | + require.Equal(t, []Person{ |
| 335 | + {ID: 1, Name: "Alice"}, |
| 336 | + {ID: 2, Name: "Bob"}, |
| 337 | + {ID: 3, Name: "Charlie"}, |
| 338 | + }, result) |
| 339 | + }) |
| 340 | + |
| 341 | + t.Run("empty-slice", func(t *testing.T) { |
| 342 | + var input []int |
| 343 | + result := DedupeFunc(input, func(i int) any { return i }) |
| 344 | + require.Empty(t, result) |
| 345 | + }) |
| 346 | + |
| 347 | + t.Run("multiple-field-key", func(t *testing.T) { |
| 348 | + type Event struct { |
| 349 | + Date string |
| 350 | + Category string |
| 351 | + Value int |
| 352 | + } |
| 353 | + input := []Event{ |
| 354 | + {"2024-01-01", "A", 1}, |
| 355 | + {"2024-01-01", "A", 2}, // Same date and category |
| 356 | + {"2024-01-01", "B", 3}, |
| 357 | + {"2024-01-02", "A", 4}, |
| 358 | + } |
| 359 | + result := DedupeFunc(input, func(e Event) any { |
| 360 | + return e.Date + "-" + e.Category |
| 361 | + }) |
| 362 | + require.Equal(t, []Event{ |
| 363 | + {"2024-01-01", "A", 1}, |
| 364 | + {"2024-01-01", "B", 3}, |
| 365 | + {"2024-01-02", "A", 4}, |
| 366 | + }, result) |
| 367 | + }) |
| 368 | + |
| 369 | + t.Run("nil-key-function", func(t *testing.T) { |
| 370 | + input := []int{1, 2, 2, 3} |
| 371 | + result := DedupeFunc(input, func(i int) any { |
| 372 | + if i == 2 { |
| 373 | + return nil |
| 374 | + } |
| 375 | + return i |
| 376 | + }) |
| 377 | + require.Equal(t, []int{1, 2, 3}, result) |
| 378 | + }) |
| 379 | + t.Run("nil-key-func", func(t *testing.T) { |
| 380 | + input := []string{"a", "b", "c"} |
| 381 | + res := DedupeFunc(input, nil) |
| 382 | + require.Equal(t, input, res) |
| 383 | + }) |
| 384 | +} |
0 commit comments