sliceutil

package
v0.0.0-...-14a125a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2025 License: MIT Imports: 10 Imported by: 0

README

sliceutil - Slice Utilities / 슬라이스 유틸리티

v1.7.023 - Extreme Simplicity for Slice Operations! 🎉

Extreme simplicity slice utility functions for Go - reduce 10-20 lines of slice manipulation code to just 1 line.

극도로 간단한 Go용 슬라이스 유틸리티 함수 - 10-20줄의 슬라이스 조작 코드를 단 1줄로 줄입니다.

Go Version

Overview / 개요

The sliceutil package provides 95 type-safe functions for common slice operations in Go. Stop writing repetitive loops and start using functional programming style.

sliceutil 패키지는 Go에서 일반적인 슬라이스 작업을 위한 95개의 타입 안전 함수를 제공합니다. 반복적인 루프 작성을 멈추고 함수형 프로그래밍 스타일을 사용하세요.

Design Philosophy: "20 lines → 1 line" / 설계 철학: "20줄 → 1줄"

Before (Standard Go) / 이전 (표준 Go):

// Filter even numbers / 짝수 필터링
numbers := []int{1, 2, 3, 4, 5, 6}
var evens []int
for _, n := range numbers {
    if n%2 == 0 {
        evens = append(evens, n)
    }
}

// Map to strings / 문자열로 매핑
var strings []string
for _, n := range evens {
    strings = append(strings, fmt.Sprintf("num_%d", n))
}

// Check if contains / 포함 확인
found := false
for _, s := range strings {
    if s == "num_4" {
        found = true
        break
    }
}
// 20+ lines of code

After (This Package) / 이후 (이 패키지):

numbers := []int{1, 2, 3, 4, 5, 6}
evens := sliceutil.Filter(numbers, func(n int) bool { return n%2 == 0 })
strings := sliceutil.Map(evens, func(n int) string { return fmt.Sprintf("num_%d", n) })
found := sliceutil.Contains(strings, "num_4")
// 3 lines of code (vs 20+)

Installation / 설치

go get github.com/arkd0ng/go-utils/sliceutil

Requirements / 요구사항:

  • Go 1.18 or higher (for generics support) / Go 1.18 이상 (제네릭 지원)

Quick Start / 빠른 시작

package main

import (
    "fmt"
    "github.com/arkd0ng/go-utils/sliceutil"
)

func main() {
    // Basic Operations / 기본 작업
    numbers := []int{1, 2, 3, 4, 5, 6}

    // Check if contains / 포함 확인
    hasThree := sliceutil.Contains(numbers, 3) // true

    // Find index / 인덱스 찾기
    index := sliceutil.IndexOf(numbers, 4) // 3

    // Transformation / 변환
    // Filter even numbers / 짝수 필터링
    evens := sliceutil.Filter(numbers, func(n int) bool {
        return n%2 == 0
    }) // [2, 4, 6]

    // Map to double / 2배로 매핑
    doubled := sliceutil.Map(numbers, func(n int) int {
        return n * 2
    }) // [2, 4, 6, 8, 10, 12]

    // Remove duplicates / 중복 제거
    items := []int{1, 2, 2, 3, 3, 3, 4}
    unique := sliceutil.Unique(items) // [1, 2, 3, 4]

    // Aggregation / 집계
    // Sum all numbers / 모든 숫자의 합
    sum := sliceutil.Sum(numbers) // 21

    // Find max / 최대값 찾기
    max, _ := sliceutil.Max(numbers) // 6

    // Group by condition / 조건으로 그룹화
    trues, falses := sliceutil.Partition(numbers, func(n int) bool {
        return n > 3
    }) // trues: [4, 5, 6], falses: [1, 2, 3]

    // Slicing / 슬라이싱
    // Take first 3 items / 처음 3개 항목
    first3 := sliceutil.Take(numbers, 3) // [1, 2, 3]

    // Split into chunks / 청크로 분할
    chunks := sliceutil.Chunk(numbers, 2) // [[1, 2], [3, 4], [5, 6]]

    // Set Operations / 집합 작업
    a := []int{1, 2, 3, 4}
    b := []int{3, 4, 5, 6}

    union := sliceutil.Union(a, b) // [1, 2, 3, 4, 5, 6]
    intersection := sliceutil.Intersection(a, b) // [3, 4]
    difference := sliceutil.Difference(a, b) // [1, 2]

    // Sorting / 정렬
    unsorted := []int{3, 1, 4, 1, 5, 9, 2}
    sorted := sliceutil.Sort(unsorted) // [1, 1, 2, 3, 4, 5, 9]

    // Predicates / 조건 검사
    // Check if all are positive / 모두 양수인지 확인
    allPositive := sliceutil.All(numbers, func(n int) bool {
        return n > 0
    }) // true

    // Check if any is greater than 5 / 5보다 큰 것이 있는지 확인
    anyGreater5 := sliceutil.Any(numbers, func(n int) bool {
        return n > 5
    }) // true

    // Utilities / 유틸리티
    // Clone slice / 슬라이스 복제
    cloned := sliceutil.Clone(numbers)

    // Shuffle / 섞기
    shuffled := sliceutil.Shuffle(numbers)

    // Join to string / 문자열로 결합
    joined := sliceutil.Join(numbers, ", ") // "1, 2, 3, 4, 5, 6"

    fmt.Println(hasThree, evens, sum, sorted, allPositive)
}

Key Features / 주요 기능

1. Type-Safe with Generics / 제네릭으로 타입 안전
// Works with any type / 모든 타입과 작동
numbers := []int{1, 2, 3}
strings := []string{"a", "b", "c"}
users := []User{{Name: "Alice"}, {Name: "Bob"}}

// Type-safe operations / 타입 안전 작업
sliceutil.Contains(numbers, 2)  // int
sliceutil.Contains(strings, "b") // string
sliceutil.Map(users, func(u User) string { return u.Name }) // User → string
2. Functional Programming Style / 함수형 프로그래밍 스타일
// Chaining operations / 작업 체이닝
result := sliceutil.Filter(
    sliceutil.Map(
        sliceutil.Unique([]int{1, 2, 2, 3, 3, 4}),
        func(n int) int { return n * 2 },
    ),
    func(n int) bool { return n > 4 },
) // [6, 8]
3. Immutable Operations / 불변 작업
// Original slice is never modified / 원본 슬라이스는 변경되지 않음
original := []int{1, 2, 3}
doubled := sliceutil.Map(original, func(n int) int { return n * 2 })
// original: [1, 2, 3] (unchanged)
// doubled: [2, 4, 6] (new slice)
4. Zero External Dependencies / 제로 외부 의존성

All functions use only the standard library.

모든 함수는 표준 라이브러리만 사용합니다.

5. Comprehensive Coverage / 포괄적인 커버리지

95 functions across 14 categories cover 99% of common slice operations.

14개 카테고리의 95개 함수가 일반적인 슬라이스 작업의 99%를 커버합니다.

Function Categories / 함수 카테고리

1. Basic Operations (11 functions) / 기본 작업 (11개 함수)

Essential operations for searching and checking slices.

슬라이스 검색 및 확인을 위한 필수 작업.

sliceutil.Contains(slice, item)           // Check if contains
sliceutil.ContainsFunc(slice, predicate)  // Check with predicate
sliceutil.IndexOf(slice, item)            // Find first index
sliceutil.LastIndexOf(slice, item)        // Find last index
sliceutil.Find(slice, predicate)          // Find first match
sliceutil.FindLast(slice, predicate)      // Find last match
sliceutil.FindIndex(slice, predicate)     // Find first match index
sliceutil.Count(slice, predicate)         // Count matches
sliceutil.IsEmpty(slice)                  // Check if empty
sliceutil.IsNotEmpty(slice)               // Check if not empty
sliceutil.Equal(a, b)                     // Compare two slices
2. Transformation (8 functions) / 변환 (8개 함수)

Transform slices into different forms.

슬라이스를 다른 형태로 변환.

sliceutil.Map(slice, mapper)              // Transform each item
sliceutil.Filter(slice, predicate)        // Keep matching items
sliceutil.FlatMap(slice, mapper)          // Map and flatten
sliceutil.Flatten(slice)                  // Flatten nested slices
sliceutil.Unique(slice)                   // Remove duplicates
sliceutil.UniqueBy(slice, keyFunc)        // Remove duplicates by key
sliceutil.Compact(slice)                  // Remove zero values
sliceutil.Reverse(slice)                  // Reverse order
3. Aggregation (11 functions) / 집계 (11개 함수)

Reduce slices to single values or group items.

슬라이스를 단일 값으로 줄이거나 항목 그룹화.

sliceutil.Reduce(slice, initial, reducer) // Custom aggregation
sliceutil.ReduceRight(slice, initial, reducer) // Reduce from right
sliceutil.Sum(slice)                      // Sum of numbers
sliceutil.Min(slice)                      // Minimum value
sliceutil.Max(slice)                      // Maximum value
sliceutil.MinBy(slice, keyFunc)           // Minimum by custom key
sliceutil.MaxBy(slice, keyFunc)           // Maximum by custom key
sliceutil.Average(slice)                  // Average of numbers
sliceutil.GroupBy(slice, keyFunc)         // Group by key
sliceutil.CountBy(slice, keyFunc)         // Count occurrences by key
sliceutil.Partition(slice, predicate)     // Split by condition
4. Slicing (11 functions) / 슬라이싱 (11개 함수)

Extract portions of slices.

슬라이스의 일부 추출.

sliceutil.Chunk(slice, size)              // Split into chunks
sliceutil.Take(slice, n)                  // Take first n items
sliceutil.TakeLast(slice, n)              // Take last n items
sliceutil.TakeWhile(slice, predicate)     // Take while predicate is true
sliceutil.Drop(slice, n)                  // Skip first n items
sliceutil.DropLast(slice, n)              // Skip last n items
sliceutil.DropWhile(slice, predicate)     // Drop while predicate is true
sliceutil.Slice(slice, start, end)        // Extract range
sliceutil.Sample(slice, n)                // Random sampling
sliceutil.Window(slice, size)             // Create sliding windows
sliceutil.Interleave(slices...)           // Interleave multiple slices
5. Set Operations (6 functions) / 집합 작업 (6개 함수)

Treat slices as mathematical sets.

슬라이스를 수학적 집합으로 처리.

sliceutil.Union(a, b)                     // Union of two slices
sliceutil.Intersection(a, b)              // Intersection of two slices
sliceutil.Difference(a, b)                // Items in a but not b
sliceutil.SymmetricDifference(a, b)       // Items in either but not both
sliceutil.IsSubset(a, b)                  // Check if a ⊆ b
sliceutil.IsSuperset(a, b)                // Check if a ⊇ b
6. Sorting (6 functions) / 정렬 (6개 함수)

Sort and check sorting order.

정렬 및 정렬 순서 확인.

sliceutil.Sort(slice)                     // Sort ascending
sliceutil.SortDesc(slice)                 // Sort descending
sliceutil.SortBy(slice, keyFunc)          // Sort by custom key
sliceutil.SortByMulti(slice, lessFunc)    // Sort by multiple keys
sliceutil.IsSorted(slice)                 // Check if sorted ascending
sliceutil.IsSortedDesc(slice)             // Check if sorted descending
7. Predicates (6 functions) / 조건 검사 (6개 함수)

Check conditions across all or some items.

모든 항목 또는 일부 항목에서 조건 확인.

sliceutil.All(slice, predicate)           // Check if all match
sliceutil.Any(slice, predicate)           // Check if any matches
sliceutil.None(slice, predicate)          // Check if none matches
sliceutil.AllEqual(slice)                 // Check if all items equal
sliceutil.IsSortedBy(slice, keyFunc)      // Check if sorted by key
sliceutil.ContainsAll(slice, items...)    // Check if contains all
8. Utilities (12 functions) / 유틸리티 (12개 함수)

Miscellaneous helpful operations.

기타 유용한 작업.

sliceutil.ForEach(slice, fn)              // Iterate with side effects
sliceutil.ForEachIndexed(slice, fn)       // Iterate with index
sliceutil.Tap(slice, fn)                  // Execute side effect and return slice
sliceutil.Join(slice, separator)          // Convert to string
sliceutil.Clone(slice)                    // Deep copy
sliceutil.Fill(slice, value)              // Fill with value
sliceutil.Insert(slice, index, items...)  // Insert at index
sliceutil.Remove(slice, index)            // Remove at index
sliceutil.RemoveAll(slice, item)          // Remove all occurrences
sliceutil.Shuffle(slice)                  // Randomize order
sliceutil.Zip(a, b)                       // Combine two slices
sliceutil.Unzip(slice)                    // Split pairs
9. Combinatorial Operations (2 functions) / 조합 작업 (2개 함수)

Generate permutations and combinations from slices.

슬라이스에서 순열과 조합 생성.

sliceutil.Permutations(slice)             // All possible permutations (n!)
sliceutil.Combinations(slice, k)          // All k-combinations C(n,k)

Performance Warning / 성능 경고:

  • Permutations grow factorially: n=5 → 120, n=10 → 3,628,800
  • Combinations: C(10,5) = 252, C(20,10) = 184,756
  • Use with caution for large slices!

성능 경고:

  • 순열은 팩토리얼로 증가: n=5 → 120, n=10 → 3,628,800
  • 조합: C(10,5) = 252, C(20,10) = 184,756
  • 큰 슬라이스에는 주의해서 사용하세요!
10. Statistics (8 functions) / 통계 (8개 함수)

Perform statistical operations on numeric slices.

숫자 슬라이스에 대한 통계 작업 수행.

sliceutil.Median(slice)                   // Calculate median
sliceutil.Mode(slice)                     // Find most frequent value
sliceutil.Frequencies(slice)              // Get frequency map
sliceutil.Percentile(slice, p)            // Calculate percentile
sliceutil.StandardDeviation(slice)        // Calculate std dev
sliceutil.Variance(slice)                 // Calculate variance
sliceutil.MostCommon(slice, n)            // Get n most common values
sliceutil.LeastCommon(slice, n)           // Get n least common values
11. Diff/Comparison (4 functions) / 차이/비교 (4개 함수)

Compare slices and detect differences.

슬라이스 비교 및 차이 감지.

sliceutil.Diff(old, new)                  // Find added/removed/unchanged
sliceutil.DiffBy(old, new, keyFunc)       // Diff by custom key
sliceutil.EqualUnordered(a, b)            // Compare ignoring order
sliceutil.HasDuplicates(slice)            // Check for duplicates
12. Index-based (3 functions) / 인덱스 기반 (3개 함수)

Operate on slices using indices.

인덱스를 사용한 슬라이스 작업.

sliceutil.FindIndices(slice, predicate)   // Find all matching indices
sliceutil.AtIndices(slice, indices)       // Get elements at indices
sliceutil.RemoveIndices(slice, indices)   // Remove elements at indices
13. Conditional (3 functions) / 조건부 (3개 함수)

Transform slices based on conditions.

조건에 따른 슬라이스 변환.

sliceutil.ReplaceIf(slice, predicate, value)  // Replace matching items
sliceutil.ReplaceAll(slice, old, new)         // Replace all occurrences
sliceutil.UpdateWhere(slice, predicate, fn)   // Update matching items
14. Advanced (4 functions) / 고급 (4개 함수)

Advanced functional programming operations.

고급 함수형 프로그래밍 작업.

sliceutil.Scan(slice, initial, fn)        // Cumulative aggregation
sliceutil.ZipWith(a, b, fn)               // Combine with custom function
sliceutil.RotateLeft(slice, n)            // Rotate left by n positions
sliceutil.RotateRight(slice, n)           // Rotate right by n positions

Real-World Examples / 실제 사용 예제

Example 1: Data Processing Pipeline / 데이터 처리 파이프라인
// Process user data / 사용자 데이터 처리
users := []User{
    {Name: "Alice", Age: 25, City: "Seoul"},
    {Name: "Bob", Age: 30, City: "Busan"},
    {Name: "Charlie", Age: 35, City: "Seoul"},
}

// Get names of Seoul users over 20 / 20세 이상의 서울 사용자 이름 가져오기
seoulAdultNames := sliceutil.Map(
    sliceutil.Filter(users, func(u User) bool {
        return u.City == "Seoul" && u.Age > 20
    }),
    func(u User) string { return u.Name },
) // ["Alice", "Charlie"]
Example 2: Data Validation / 데이터 검증
// Check if all prices are positive / 모든 가격이 양수인지 확인
prices := []float64{10.5, 20.0, 30.25, 15.75}
allPositive := sliceutil.All(prices, func(p float64) bool {
    return p > 0
}) // true

// Check if any price is over 100 / 100 이상의 가격이 있는지 확인
anyExpensive := sliceutil.Any(prices, func(p float64) bool {
    return p > 100
}) // false
Example 3: Data Aggregation / 데이터 집계
// Group orders by status / 상태별 주문 그룹화
orders := []Order{
    {ID: 1, Status: "pending"},
    {ID: 2, Status: "shipped"},
    {ID: 3, Status: "pending"},
}

byStatus := sliceutil.GroupBy(orders, func(o Order) string {
    return o.Status
})
// map[string][]Order{
//     "pending": [{1, "pending"}, {3, "pending"}],
//     "shipped": [{2, "shipped"}],
// }
Example 4: Batch Processing / 배치 처리
// Process items in batches of 100 / 100개씩 배치 처리
items := make([]int, 1000)
batches := sliceutil.Chunk(items, 100) // 10 batches of 100 items

for _, batch := range batches {
    processBatch(batch)
}
Example 5: Set Operations / 집합 작업
// Find common tags between posts / 게시물 간 공통 태그 찾기
post1Tags := []string{"go", "programming", "backend"}
post2Tags := []string{"go", "web", "programming"}

commonTags := sliceutil.Intersection(post1Tags, post2Tags)
// ["go", "programming"]

allTags := sliceutil.Union(post1Tags, post2Tags)
// ["go", "programming", "backend", "web"]

Performance / 성능

All functions are implemented with performance in mind:

모든 함수는 성능을 고려하여 구현되었습니다:

  • Efficient algorithms / 효율적인 알고리즘
  • Minimal allocations / 최소한의 할당
  • Benchmark tests included / 벤치마크 테스트 포함

For performance-critical code, consider:

성능이 중요한 코드의 경우 다음을 고려하세요:

  1. Use preallocated slices when possible / 가능한 경우 미리 할당된 슬라이스 사용
  2. Avoid unnecessary transformations / 불필요한 변환 방지
  3. Check benchmarks for your use case / 사용 사례에 대한 벤치마크 확인

Documentation / 문서

For more detailed documentation:

더 자세한 문서:

  • User Manual - Comprehensive guide with examples / 예제가 있는 포괄적인 가이드
  • Developer Guide - Architecture and implementation details / 아키텍처 및 구현 세부사항
  • Design Plan - Design philosophy and decisions / 설계 철학 및 결정
  • Work Plan - Implementation roadmap / 구현 로드맵

Testing / 테스트

Run tests:

테스트 실행:

# Run all tests / 모든 테스트 실행
go test ./sliceutil -v

# Run with coverage / 커버리지와 함께 실행
go test ./sliceutil -cover

# Run benchmarks / 벤치마크 실행
go test ./sliceutil -bench=.

Contributing / 기여하기

Contributions are welcome! Please see CONTRIBUTING.md for details.

기여를 환영합니다! 자세한 내용은 CONTRIBUTING.md를 참조하세요.

License / 라이선스

MIT License - see LICENSE for details.

MIT 라이선스 - 자세한 내용은 LICENSE를 참조하세요.

Version / 버전

Current version: v1.7.023

For version history, see CHANGELOG-v1.7.md.

버전 히스토리는 CHANGELOG-v1.7.md를 참조하세요.

Support / 지원


Made with ❤️ by arkd0ng

Part of go-utils - A collection of utility packages for Go

Documentation

Overview

Package sliceutil provides extreme simplicity for slice operations in Go.

# Design Philosophy 설계 철학

"20 lines → 1 line" - Reduce repetitive slice manipulation code to simple function calls.

"20줄 → 1줄" - 반복적인 슬라이스 조작 코드를 간단한 함수 호출로 줄입니다.

# Overview 개요

This package provides 95 functions across 14 categories for common slice operations:

이 패키지는 일반적인 슬라이스 작업을 위한 14개 카테고리에 걸쳐 95개의 함수를 제공합니다:

  1. Basic Operations (11 functions) - Contains, IndexOf, Find, FindLast, Count, etc.
  2. Transformation (8 functions) - Map, Filter, Unique, Reverse, Flatten, FlatMap, etc.
  3. Aggregation (11 functions) - Reduce, ReduceRight, Sum, Min, Max, MinBy, MaxBy, Average, GroupBy, CountBy, Partition
  4. Slicing (10 functions) - Chunk, Take, TakeLast, Drop, DropLast, TakeWhile, DropWhile, Slice, Sample, Interleave
  5. Set Operations (6 functions) - Union, Intersection, Difference, SymmetricDifference, IsSubset, IsSuperset
  6. Sorting (6 functions) - Sort, SortDesc, SortBy, SortByMulti, IsSorted, IsSortedDesc
  7. Predicates (6 functions) - All, Any, None, AllEqual, ContainsAll, IsSortedBy
  8. Utilities (13 functions) - ForEach, ForEachIndexed, Join, Clone, Fill, Insert, Remove, RemoveAll, Shuffle, Zip, Unzip, Window, Tap
  9. Combinatorial (2 functions) - Permutations, Combinations

10. Statistics (8 functions) - Median, Mode, Frequencies, Percentile, StandardDeviation, Variance, MostCommon, LeastCommon 11. Diff/Comparison (4 functions) - Diff, DiffBy, EqualUnordered, HasDuplicates 12. Index-based (3 functions) - FindIndices, AtIndices, RemoveIndices 13. Conditional (3 functions) - ReplaceIf, ReplaceAll, UpdateWhere 14. Advanced (4 functions) - Scan, ZipWith, RotateLeft, RotateRight

# Key Features 주요 기능

- Type-safe with Go 1.18+ generics Go 1.18+ 제네릭으로 타입 안전 - Functional programming style 함수형 프로그래밍 스타일 - Immutable operations 불변 작업 - Zero external dependencies 제로 외부 의존성 - Comprehensive coverage of common operations 일반적인 작업의 포괄적인 커버리지

# Example 예제

Before (Standard Go):

// Filter even numbers
numbers := []int{1, 2, 3, 4, 5, 6}
var evens []int
for _, n := range numbers {
    if n%2 == 0 {
        evens = append(evens, n)
    }
}
// 8+ lines of code

After (This Package):

numbers := []int{1, 2, 3, 4, 5, 6}
evens := sliceutil.Filter(numbers, func(n int) bool { return n%2 == 0 })
// 1 line of code (vs 8+)

# Usage 사용법

Import the package:

import "github.com/arkd0ng/go-utils/sliceutil"

Use any function:

// Basic Operations 기본 작업

found := sliceutil.Contains([]int{1, 2, 3}, 2)
index := sliceutil.IndexOf([]string{"a", "b", "c"}, "b")

// Transformation 변환

doubled := sliceutil.Map([]int{1, 2, 3}, func(n int) int { return n * 2 })
evens := sliceutil.Filter([]int{1, 2, 3, 4}, func(n int) bool { return n%2 == 0 })
unique := sliceutil.Unique([]int{1, 2, 2, 3, 3, 3})

// Aggregation 집계

sum := sliceutil.Sum([]int{1, 2, 3, 4, 5})
max, _ := sliceutil.Max([]int{1, 5, 3, 9, 2})
grouped := sliceutil.GroupBy(users, func(u User) string { return u.City })

// Set Operations 집합 작업

union := sliceutil.Union([]int{1, 2, 3}, []int{3, 4, 5})
intersection := sliceutil.Intersection([]int{1, 2, 3}, []int{2, 3, 4})

# Performance 성능

All functions are implemented with performance in mind, using efficient algorithms and minimal allocations. For performance-critical code, benchmarks are provided.

모든 함수는 효율적인 알고리즘과 최소한의 할당을 사용하여 성능을 고려하여 구현되었습니다. 성능이 중요한 코드의 경우 벤치마크가 제공됩니다.

# Version 버전

Current version is loaded automatically from cfg/app.yaml. 현재 버전은 cfg/app.yaml에서 자동으로 로드됩니다.

For more information, see:

Index

Constants

This section is empty.

Variables

View Source
var Version = version.Get()

Version is the current package version loaded from cfg/app.yaml. Version은 cfg/app.yaml에서 로드되는 현재 패키지 버전입니다.

Functions

func All

func All[T any](slice []T, predicate func(T) bool) bool

All checks if all elements in the slice satisfy the predicate. All은 슬라이스의 모든 요소가 조건을 만족하는지 확인합니다.

Returns true if all elements satisfy the predicate, false otherwise. 모든 요소가 조건을 만족하면 true를, 그렇지 않으면 false를 반환합니다.

An empty slice returns true (vacuous truth). 비어있는 슬라이스는 true를 반환합니다 (공허한 진리).

Example 예제:

numbers := []int{2, 4, 6, 8}
allEven := sliceutil.All(numbers, func(n int) bool { return n%2 == 0 })
// allEven: true

numbers2 := []int{2, 4, 5, 8}
allEven2 := sliceutil.All(numbers2, func(n int) bool { return n%2 == 0 })
// allEven2: false

func AllEqual

func AllEqual[T comparable](slice []T) bool

AllEqual checks if all elements in the slice are equal. AllEqual은 슬라이스의 모든 요소가 같은지 확인합니다.

Returns true if all elements are equal, false otherwise. 모든 요소가 같으면 true를, 그렇지 않으면 false를 반환합니다.

An empty slice returns true. 비어있는 슬라이스는 true를 반환합니다.

A slice with one element returns true. 요소가 하나인 슬라이스는 true를 반환합니다.

Example 예제:

numbers := []int{5, 5, 5, 5}
allSame := sliceutil.AllEqual(numbers)
// allSame: true

numbers2 := []int{5, 5, 6, 5}
allSame2 := sliceutil.AllEqual(numbers2)
// allSame2: false

func Any

func Any[T any](slice []T, predicate func(T) bool) bool

Any checks if at least one element in the slice satisfies the predicate. Any는 슬라이스의 최소한 하나의 요소가 조건을 만족하는지 확인합니다.

Returns true if at least one element satisfies the predicate, false otherwise. 최소한 하나의 요소가 조건을 만족하면 true를, 그렇지 않으면 false를 반환합니다.

An empty slice returns false. 비어있는 슬라이스는 false를 반환합니다.

Example 예제:

numbers := []int{1, 3, 5, 6}
hasEven := sliceutil.Any(numbers, func(n int) bool { return n%2 == 0 })
// hasEven: true

numbers2 := []int{1, 3, 5, 7}
hasEven2 := sliceutil.Any(numbers2, func(n int) bool { return n%2 == 0 })
// hasEven2: false

func AtIndices

func AtIndices[T any](slice []T, indices []int) []T

AtIndices returns elements at the specified indices. Indices that are out of bounds are silently skipped. Negative indices are not supported and will be skipped.

AtIndices는 지정된 인덱스의 요소를 반환합니다. 범위를 벗어난 인덱스는 자동으로 건너뜁니다. 음수 인덱스는 지원되지 않으며 건너뜁니다.

Example:

numbers := []int{10, 20, 30, 40, 50}
selected := sliceutil.AtIndices(numbers, []int{0, 2, 4})
// [10, 30, 50]

// Out of bounds indices are skipped
selected := sliceutil.AtIndices(numbers, []int{0, 10, 2})
// [10, 30]

func Average

func Average[T constraints.Integer | constraints.Float](slice []T) float64

Average returns the average of all elements in the slice. Returns 0 if the slice is empty. Average는 슬라이스의 모든 요소의 평균을 반환합니다. 슬라이스가 비어있으면 0을 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
avg := sliceutil.Average(numbers) // 3.0

floats := []float64{1.5, 2.5, 3.0}
avg := sliceutil.Average(floats) // 2.333...

func Chunk

func Chunk[T any](slice []T, size int) [][]T

Chunk splits a slice into chunks of the specified size. The last chunk may be smaller than the specified size. Chunk는 슬라이스를 지정된 크기의 청크로 분할합니다. 마지막 청크는 지정된 크기보다 작을 수 있습니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5, 6, 7}
chunks := sliceutil.Chunk(numbers, 3) // [[1, 2, 3], [4, 5, 6], [7]]

words := []string{"a", "b", "c", "d", "e"}
chunks := sliceutil.Chunk(words, 2) // [["a", "b"], ["c", "d"], ["e"]]

func Clone

func Clone[T any](slice []T) []T

Clone creates a shallow copy of the slice. Clone은 슬라이스의 얕은 복사본을 생성합니다.

The returned slice has the same elements but is a different underlying array. 반환된 슬라이스는 동일한 요소를 가지지만 다른 기본 배열입니다.

Example 예제:

original := []int{1, 2, 3, 4, 5}
cloned := sliceutil.Clone(original)

cloned[0] = 99 original: [1, 2, 3, 4, 5] (unchanged 변경되지 않음)

// cloned: [99, 2, 3, 4, 5]

func Combinations

func Combinations[T any](slice []T, k int) [][]T

Combinations returns all possible combinations of k elements from the slice. Returns a slice of slices, where each sub-slice is a combination. Warning: The number of combinations is C(n, k) = n! (k! * (n-k)!). Combinations는 슬라이스에서 k개 요소의 모든 가능한 조합을 반환합니다. 각 하위 슬라이스가 조합인 슬라이스의 슬라이스를 반환합니다. 경고: 조합의 수는 C(n, k) = n! (k! * (n-k)!)입니다.

Example 예제:

numbers := []int{1, 2, 3, 4}
combs := sliceutil.Combinations(numbers, 2)
// combs: [[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]

letters := []string{"a", "b", "c"}
combs := sliceutil.Combinations(letters, 2)
// combs: [["a","b"], ["a","c"], ["b","c"]]

Performance note 성능 참고:

C(10, 5) = 252 combinations
C(20, 10) = 184,756 combinations
Use with caution for large values!

func Compact

func Compact[T comparable](slice []T) []T

Compact removes consecutive duplicate elements from the slice. Compact는 슬라이스에서 연속된 중복 요소를 제거합니다.

Example 예제:

numbers := []int{1, 2, 2, 3, 3, 3, 4, 4, 5}
compact := sliceutil.Compact(numbers) // [1, 2, 3, 4, 5]

words := []string{"a", "a", "b", "b", "c"}
compact := sliceutil.Compact(words) // ["a", "b", "c"]

func Contains

func Contains[T comparable](slice []T, item T) bool

Contains checks if slice contains the specified item. Contains는 슬라이스에 지정된 항목이 있는지 확인합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
hasThree := sliceutil.Contains(numbers, 3) // true
hasTen := sliceutil.Contains(numbers, 10)  // false

func ContainsAll

func ContainsAll[T comparable](slice []T, items ...T) bool

ContainsAll checks if the slice contains all of the specified items. ContainsAll은 슬라이스가 지정된 모든 항목을 포함하는지 확인합니다.

Returns true if the slice contains all specified items, false otherwise. 슬라이스가 지정된 모든 항목을 포함하면 true를, 그렇지 않으면 false를 반환합니다.

If no items are specified, returns true. 항목이 지정되지 않은 경우 true를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
hasAll := sliceutil.ContainsAll(numbers, 2, 4)
// hasAll: true

hasAll2 := sliceutil.ContainsAll(numbers, 2, 6)
// hasAll2: false

func ContainsFunc

func ContainsFunc[T any](slice []T, predicate func(T) bool) bool

ContainsFunc checks if slice contains an item that satisfies the predicate. ContainsFunc는 조건을 만족하는 항목이 슬라이스에 있는지 확인합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
hasEven := sliceutil.ContainsFunc(numbers, func(n int) bool {
    return n%2 == 0
}) // true (has 2, 4)

func Count

func Count[T any](slice []T, predicate func(T) bool) int

Count returns the number of items that satisfy the predicate. Count는 조건을 만족하는 항목의 개수를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5, 6}
evenCount := sliceutil.Count(numbers, func(n int) bool {
    return n%2 == 0
}) // 3 (2, 4, 6)

func CountBy

func CountBy[T any, K comparable](slice []T, keyFunc func(T) K) map[K]int

CountBy counts elements by a key function and returns a map with counts. CountBy는 키 함수로 요소를 세고 개수를 포함한 맵을 반환합니다.

Similar to GroupBy, but returns counts instead of grouped elements. GroupBy와 유사하지만 그룹화된 요소 대신 개수를 반환합니다.

Example 예제:

type Person struct {
    Name string
    Age  int
}
people := []Person{
    {"Alice", 25},
    {"Bob", 30},
    {"Charlie", 25},
}
counts := sliceutil.CountBy(people, func(p Person) int {
    return p.Age
}) // map[25:2 30:1]

numbers := []int{1, 2, 3, 4, 5, 6}
counts := sliceutil.CountBy(numbers, func(n int) string {
    if n%2 == 0 {
        return "even"
    }
    return "odd"
}) // map["even":3 "odd":3]

func Difference

func Difference[T comparable](a, b []T) []T

Difference returns the difference of two slices (elements in a but not in b). Difference는 두 슬라이스의 차집합을 반환합니다 (a에 있지만 b에 없는 요소).

Example 예제:

a := []int{1, 2, 3, 4}
b := []int{3, 4, 5, 6}
diff := sliceutil.Difference(a, b) // [1, 2]

words1 := []string{"apple", "banana", "cherry"}
words2 := []string{"banana", "date"}
diff := sliceutil.Difference(words1, words2) // ["apple", "cherry"]

func Drop

func Drop[T any](slice []T, n int) []T

Drop returns a slice without the first n elements. If n is greater than the slice length, returns an empty slice. Drop은 첫 n개 요소를 제외한 슬라이스를 반환합니다. n이 슬라이스 길이보다 크면 빈 슬라이스를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
rest := sliceutil.Drop(numbers, 2) // [3, 4, 5]

words := []string{"hello", "world", "foo"}
rest := sliceutil.Drop(words, 1) // ["world", "foo"]

func DropLast

func DropLast[T any](slice []T, n int) []T

DropLast returns a slice without the last n elements. If n is greater than the slice length, returns an empty slice. DropLast는 마지막 n개 요소를 제외한 슬라이스를 반환합니다. n이 슬라이스 길이보다 크면 빈 슬라이스를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
rest := sliceutil.DropLast(numbers, 2) // [1, 2, 3]

words := []string{"hello", "world", "foo"}
rest := sliceutil.DropLast(words, 1) // ["hello", "world"]

func DropWhile

func DropWhile[T any](slice []T, predicate func(T) bool) []T

DropWhile returns elements after dropping the beginning while predicate is true. Starts including elements from the first one that doesn't satisfy the predicate. DropWhile은 조건이 참인 동안 처음 요소를 제거한 후 요소를 반환합니다. 조건을 만족하지 않는 첫 번째 요소부터 포함하기 시작합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 1, 2}
result := sliceutil.DropWhile(numbers, func(n int) bool {
    return n < 4
}) // [4, 1, 2]

words := []string{"apple", "apricot", "banana", "avocado"}
result := sliceutil.DropWhile(words, func(s string) bool {
    return len(s) > 0 && s[0] == 'a'
}) // ["banana", "avocado"]

func Equal

func Equal[T comparable](a, b []T) bool

Equal checks if two slices are equal (same length and same elements in same order). Equal은 두 슬라이스가 같은지 확인합니다 (같은 길이와 같은 순서의 같은 요소).

Example 예제:

a := []int{1, 2, 3}
b := []int{1, 2, 3}
c := []int{1, 2, 4}

sliceutil.Equal(a, b) // true
sliceutil.Equal(a, c) // false

func EqualUnordered

func EqualUnordered[T comparable](a, b []T) bool

EqualUnordered checks if two slices contain the same elements, regardless of order. Returns true if both slices have the same elements with the same frequencies.

EqualUnordered는 순서에 관계없이 두 슬라이스가 같은 요소를 포함하는지 확인합니다. 양쪽 슬라이스가 같은 빈도의 같은 요소를 가지면 true를 반환합니다.

Example:

a := []int{1, 2, 3, 2}
b := []int{3, 2, 1, 2}
equal := sliceutil.EqualUnordered(a, b) // true

c := []int{1, 2, 3}
d := []int{1, 2, 3, 3}
equal := sliceutil.EqualUnordered(c, d) // false (different frequencies)

func Fill

func Fill[T any](slice []T, value T) []T

Fill replaces all elements in the slice with the specified value. Fill은 슬라이스의 모든 요소를 지정된 값으로 바꿉니다.

Returns a new slice with all elements set to the value. 모든 요소가 값으로 설정된 새 슬라이스를 반환합니다.

Example 예제:

slice := []int{1, 2, 3, 4, 5}
filled := sliceutil.Fill(slice, 0)

// filled: [0, 0, 0, 0, 0] slice: [1, 2, 3, 4, 5] (unchanged 변경되지 않음)

func Filter

func Filter[T any](slice []T, predicate func(T) bool) []T

Filter returns a new slice containing only elements that satisfy the predicate. Filter는 조건을 만족하는 요소만 포함하는 새 슬라이스를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5, 6}
evens := sliceutil.Filter(numbers, func(n int) bool {
    return n%2 == 0
}) // [2, 4, 6]

words := []string{"apple", "a", "banana", "pear", "ab"}
long := sliceutil.Filter(words, func(s string) bool {
    return len(s) > 2
}) // ["apple", "banana", "pear"]

func Find

func Find[T any](slice []T, predicate func(T) bool) (T, bool)

Find returns the first item in slice that satisfies the predicate. Returns the found item and true if found, zero value and false otherwise.

Find는 조건을 만족하는 슬라이스의 첫 번째 항목을 반환합니다. 찾은 경우 항목과 true를 반환하고, 그렇지 않으면 제로 값과 false를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
even, found := sliceutil.Find(numbers, func(n int) bool {
    return n%2 == 0
}) // even = 2, found = true

negative, found := sliceutil.Find(numbers, func(n int) bool {
    return n < 0
}) // negative = 0, found = false

func FindIndex

func FindIndex[T any](slice []T, predicate func(T) bool) int

FindIndex returns the index of the first item that satisfies the predicate. Returns -1 if no item is found.

FindIndex는 조건을 만족하는 첫 번째 항목의 인덱스를 반환합니다. 항목을 찾을 수 없으면 -1을 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
index := sliceutil.FindIndex(numbers, func(n int) bool {
    return n%2 == 0
}) // 1 (index of 2)

func FindIndices

func FindIndices[T any](slice []T, predicate func(T) bool) []int

FindIndices returns all indices where the predicate returns true. Returns an empty slice if no elements match.

FindIndices는 조건이 true를 반환하는 모든 인덱스를 반환합니다. 일치하는 요소가 없으면 빈 슬라이스를 반환합니다.

Example:

numbers := []int{1, 2, 3, 4, 5, 6}
evenIndices := sliceutil.FindIndices(numbers, func(n int) bool {
    return n%2 == 0
}) // [1, 3, 5] (indices of 2, 4, 6)

func FindLast

func FindLast[T any](slice []T, predicate func(T) bool) (T, bool)

FindLast returns the last item in slice that satisfies the predicate. Returns the found item and true if found, zero value and false otherwise.

FindLast는 조건을 만족하는 슬라이스의 마지막 항목을 반환합니다. 찾은 경우 항목과 true를 반환하고, 그렇지 않으면 제로 값과 false를 반환합니다.

Similar to Find, but searches from right to left. Find와 유사하지만 오른쪽에서 왼쪽으로 검색합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5, 6}
even, found := sliceutil.FindLast(numbers, func(n int) bool {
    return n%2 == 0
}) // even = 6, found = true (last even number)

words := []string{"apple", "banana", "apricot", "cherry"}
startsWithA, found := sliceutil.FindLast(words, func(s string) bool {
    return len(s) > 0 && s[0] == 'a'
}) // startsWithA = "apricot", found = true

func FlatMap

func FlatMap[T any, R any](slice []T, fn func(T) []R) []R

FlatMap applies a function to each element and flattens the results into a single slice. FlatMap은 각 요소에 함수를 적용하고 결과를 하나의 슬라이스로 평탄화합니다.

Example 예제:

words := []string{"hello", "world"}
chars := sliceutil.FlatMap(words, func(s string) []rune {
    return []rune(s)
}) // ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

numbers := []int{1, 2, 3}
pairs := sliceutil.FlatMap(numbers, func(n int) []int {
    return []int{n, n * 2}
}) // [1, 2, 2, 4, 3, 6]

func Flatten

func Flatten[T any](slice [][]T) []T

Flatten flattens a slice of slices into a single slice. Flatten은 슬라이스의 슬라이스를 하나의 슬라이스로 평탄화합니다.

Example 예제:

nested := [][]int{{1, 2}, {3, 4}, {5}}
flat := sliceutil.Flatten(nested) // [1, 2, 3, 4, 5]

words := [][]string{{"hello", "world"}, {"foo", "bar"}}
flat := sliceutil.Flatten(words) // ["hello", "world", "foo", "bar"]

func ForEach

func ForEach[T any](slice []T, fn func(T))

ForEach executes a function for each element in the slice. ForEach는 슬라이스의 각 요소에 대해 함수를 실행합니다.

The function is executed for its side effects; ForEach does not return a value. 함수는 부수 효과를 위해 실행됩니다; ForEach는 값을 반환하지 않습니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
sliceutil.ForEach(numbers, func(n int) {
    fmt.Println(n * 2)
})
// Output: 2, 4, 6, 8, 10 (each on a new line)

func ForEachIndexed

func ForEachIndexed[T any](slice []T, fn func(int, T))

ForEachIndexed executes a function for each element in the slice with its index. ForEachIndexed는 슬라이스의 각 요소와 인덱스에 대해 함수를 실행합니다.

The function receives both the index and the element. 함수는 인덱스와 요소를 모두 받습니다.

Example 예제:

words := []string{"apple", "banana", "cherry"}
sliceutil.ForEachIndexed(words, func(i int, word string) {
    fmt.Printf("%d: %s\n", i, word)
})
// Output:
// 0: apple
// 1: banana
// 2: cherry

func Frequencies

func Frequencies[T comparable](slice []T) map[T]int

Frequencies returns a map of each element to its frequency count in the slice.

Frequencies는 슬라이스의 각 요소를 빈도 수에 매핑한 맵을 반환합니다.

Example:

numbers := []int{1, 2, 2, 3, 3, 3, 4}
freq := sliceutil.Frequencies(numbers) // map[1:1 2:2 3:3 4:1]

func GroupBy

func GroupBy[T any, K comparable](slice []T, keyFunc func(T) K) map[K][]T

GroupBy groups elements by a key function and returns a map. GroupBy는 키 함수로 요소를 그룹화하고 맵을 반환합니다.

Example 예제:

type Person struct {
    Name string
    Age  int
}
people := []Person{
    {"Alice", 25},
    {"Bob", 30},
    {"Charlie", 25},
}
grouped := sliceutil.GroupBy(people, func(p Person) int {
    return p.Age
}) // map[25:[{Alice 25} {Charlie 25}] 30:[{Bob 30}]]

numbers := []int{1, 2, 3, 4, 5, 6}
grouped := sliceutil.GroupBy(numbers, func(n int) string {
    if n%2 == 0 {
        return "even"
    }
    return "odd"
}) // map["even":[2 4 6] "odd":[1 3 5]]

func HasDuplicates

func HasDuplicates[T comparable](slice []T) bool

HasDuplicates checks if a slice contains any duplicate elements. Returns true if there are duplicates, false otherwise.

HasDuplicates는 슬라이스에 중복 요소가 있는지 확인합니다. 중복이 있으면 true를, 없으면 false를 반환합니다.

Example:

numbers := []int{1, 2, 3, 2, 4}
hasDups := sliceutil.HasDuplicates(numbers) // true

unique := []int{1, 2, 3, 4, 5}
hasDups := sliceutil.HasDuplicates(unique) // false

func IndexOf

func IndexOf[T comparable](slice []T, item T) int

IndexOf returns the index of the first occurrence of item in slice. Returns -1 if item is not found.

IndexOf는 슬라이스에서 항목의 첫 번째 발생 인덱스를 반환합니다. 항목을 찾을 수 없으면 -1을 반환합니다.

Example 예제:

fruits := []string{"apple", "banana", "cherry", "banana"}
index := sliceutil.IndexOf(fruits, "banana") // 1
index2 := sliceutil.IndexOf(fruits, "grape") // -1

func Insert

func Insert[T any](slice []T, index int, items ...T) []T

Insert inserts items at the specified index. Insert는 지정된 인덱스에 항목을 삽입합니다.

Returns a new slice with items inserted at the index. 인덱스에 항목이 삽입된 새 슬라이스를 반환합니다.

If index is negative or greater than slice length, items are appended. 인덱스가 음수이거나 슬라이스 길이보다 크면 항목이 추가됩니다.

Example 예제:

slice := []int{1, 2, 5, 6}
result := sliceutil.Insert(slice, 2, 3, 4)
// result: [1, 2, 3, 4, 5, 6]

result2 := sliceutil.Insert(slice, 0, 0)
// result2: [0, 1, 2, 5, 6]

func Interleave

func Interleave[T any](slices ...[]T) []T

Interleave merges multiple slices by taking one element from each in turn. Continues until all slices are exhausted. Interleave은 각 슬라이스에서 차례로 하나씩 요소를 가져와 여러 슬라이스를 병합합니다. 모든 슬라이스가 소진될 때까지 계속합니다.

Example 예제:

a := []int{1, 2, 3}
b := []int{10, 20, 30}
c := []int{100, 200}
result := sliceutil.Interleave(a, b, c)
// result: [1, 10, 100, 2, 20, 200, 3, 30]

words1 := []string{"a", "b"}
words2 := []string{"x", "y", "z"}
result := sliceutil.Interleave(words1, words2)
// result: ["a", "x", "b", "y", "z"]

func Intersection

func Intersection[T comparable](a, b []T) []T

Intersection returns the intersection of two slices (common elements). Intersection은 두 슬라이스의 교집합을 반환합니다 (공통 요소).

Example 예제:

a := []int{1, 2, 3, 4}
b := []int{3, 4, 5, 6}
common := sliceutil.Intersection(a, b) // [3, 4]

words1 := []string{"apple", "banana", "cherry"}
words2 := []string{"banana", "cherry", "date"}
common := sliceutil.Intersection(words1, words2) // ["banana", "cherry"]

func IsEmpty

func IsEmpty[T any](slice []T) bool

IsEmpty checks if the slice is empty or nil. IsEmpty는 슬라이스가 비어있거나 nil인지 확인합니다.

Example 예제:

empty := []int{}
sliceutil.IsEmpty(empty) // true
sliceutil.IsEmpty(nil)   // true

nonEmpty := []int{1, 2, 3}
sliceutil.IsEmpty(nonEmpty) // false

func IsNotEmpty

func IsNotEmpty[T any](slice []T) bool

IsNotEmpty checks if the slice has at least one item. IsNotEmpty는 슬라이스에 최소한 하나의 항목이 있는지 확인합니다.

Example 예제:

empty := []int{}
sliceutil.IsNotEmpty(empty) // false

nonEmpty := []int{1, 2, 3}
sliceutil.IsNotEmpty(nonEmpty) // true

func IsSorted

func IsSorted[T constraints.Ordered](slice []T) bool

IsSorted checks if the slice is sorted in ascending order. IsSorted는 슬라이스가 오름차순으로 정렬되어 있는지 확인합니다.

Returns true if the slice is sorted in ascending order, false otherwise. 슬라이스가 오름차순으로 정렬되어 있으면 true를, 그렇지 않으면 false를 반환합니다.

An empty slice or a slice with one element is considered sorted. 비어있는 슬라이스나 요소가 하나인 슬라이스는 정렬된 것으로 간주됩니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
isSorted := sliceutil.IsSorted(numbers)  // true

numbers2 := []int{5, 4, 3, 2, 1}
isSorted2 := sliceutil.IsSorted(numbers2)  // false

func IsSortedBy

func IsSortedBy[T any, K constraints.Ordered](slice []T, keyFunc func(T) K) bool

IsSortedBy checks if the slice is sorted in ascending order by the key extracted by keyFunc. IsSortedBy는 keyFunc으로 추출한 키를 기준으로 슬라이스가 오름차순으로 정렬되어 있는지 확인합니다.

Returns true if the slice is sorted in ascending order by the extracted key, false otherwise. 추출한 키를 기준으로 슬라이스가 오름차순으로 정렬되어 있으면 true를, 그렇지 않으면 false를 반환합니다.

An empty slice or a slice with one element is considered sorted. 비어있는 슬라이스나 요소가 하나인 슬라이스는 정렬된 것으로 간주됩니다.

Example 예제:

type Person struct {
    Name string
    Age  int
}
people := []Person{
    {"Alice", 25},
    {"Bob", 30},
    {"Charlie", 35},
}
isSortedByAge := sliceutil.IsSortedBy(people, func(p Person) int { return p.Age })
// isSortedByAge: true

func IsSortedDesc

func IsSortedDesc[T constraints.Ordered](slice []T) bool

IsSortedDesc checks if the slice is sorted in descending order. IsSortedDesc는 슬라이스가 내림차순으로 정렬되어 있는지 확인합니다.

Returns true if the slice is sorted in descending order, false otherwise. 슬라이스가 내림차순으로 정렬되어 있으면 true를, 그렇지 않으면 false를 반환합니다.

An empty slice or a slice with one element is considered sorted. 비어있는 슬라이스나 요소가 하나인 슬라이스는 정렬된 것으로 간주됩니다.

Example 예제:

numbers := []int{5, 4, 3, 2, 1}
isSortedDesc := sliceutil.IsSortedDesc(numbers)  // true

numbers2 := []int{1, 2, 3, 4, 5}
isSortedDesc2 := sliceutil.IsSortedDesc(numbers2)  // false

func IsSubset

func IsSubset[T comparable](a, b []T) bool

IsSubset returns true if a is a subset of b (all elements of a are in b). IsSubset은 a가 b의 부분집합이면 true를 반환합니다 (a의 모든 요소가 b에 있음).

Example 예제:

a := []int{1, 2}
b := []int{1, 2, 3, 4}
isSubset := sliceutil.IsSubset(a, b) // true

a := []int{1, 5}
b := []int{1, 2, 3, 4}
isSubset := sliceutil.IsSubset(a, b) // false

func IsSuperset

func IsSuperset[T comparable](a, b []T) bool

IsSuperset returns true if a is a superset of b (all elements of b are in a). IsSuperset은 a가 b의 상위집합이면 true를 반환합니다 (b의 모든 요소가 a에 있음).

Example 예제:

a := []int{1, 2, 3, 4}
b := []int{1, 2}
isSuperset := sliceutil.IsSuperset(a, b) // true

a := []int{1, 2, 3}
b := []int{1, 5}
isSuperset := sliceutil.IsSuperset(a, b) // false

func Join

func Join[T any](slice []T, separator string) string

Join converts all elements to strings and joins them with the separator. Join은 모든 요소를 문자열로 변환하고 구분자로 결합합니다.

Uses fmt.Sprint to convert elements to strings. fmt.Sprint를 사용하여 요소를 문자열로 변환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
result := sliceutil.Join(numbers, ", ")
// result: "1, 2, 3, 4, 5"

words := []string{"apple", "banana", "cherry"}
result2 := sliceutil.Join(words, "-")
// result2: "apple-banana-cherry"

func LastIndexOf

func LastIndexOf[T comparable](slice []T, item T) int

LastIndexOf returns the index of the last occurrence of item in slice. Returns -1 if item is not found.

LastIndexOf는 슬라이스에서 항목의 마지막 발생 인덱스를 반환합니다. 항목을 찾을 수 없으면 -1을 반환합니다.

Example 예제:

fruits := []string{"apple", "banana", "cherry", "banana"}
index := sliceutil.LastIndexOf(fruits, "banana") // 3
index2 := sliceutil.LastIndexOf(fruits, "grape") // -1

func LeastCommon

func LeastCommon[T comparable](slice []T, n int) []T

LeastCommon returns the n least frequently occurring elements in the slice, in ascending order of frequency. If there are ties, elements are ordered by their first occurrence in the slice. If n is greater than the number of unique elements, returns all unique elements.

LeastCommon은 슬라이스에서 가장 적게 나타나는 n개의 요소를 빈도의 오름차순으로 반환합니다. 동점이 있는 경우 슬라이스에서 처음 나타난 순서대로 정렬됩니다. n이 고유 요소의 수보다 크면 모든 고유 요소를 반환합니다.

Example:

numbers := []int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4}
bottom2 := sliceutil.LeastCommon(numbers, 2) // [1, 2]

func Map

func Map[T any, R any](slice []T, fn func(T) R) []R

Map applies a function to each element and returns a new slice with the results. Map은 각 요소에 함수를 적용하고 결과로 새 슬라이스를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
doubled := sliceutil.Map(numbers, func(n int) int {
    return n * 2
}) // [2, 4, 6, 8, 10]

words := []string{"hello", "world"}
lengths := sliceutil.Map(words, func(s string) int {
    return len(s)
}) // [5, 5]

func Max

func Max[T constraints.Ordered](slice []T) (T, error)

Max returns the maximum element in the slice. Returns an error if the slice is empty. Max는 슬라이스의 최대 요소를 반환합니다. 슬라이스가 비어있으면 에러를 반환합니다.

Example 예제:

numbers := []int{3, 1, 4, 1, 5}
max, _ := sliceutil.Max(numbers) // 5

words := []string{"banana", "apple", "cherry"}
max, _ := sliceutil.Max(words) // "cherry"

func MaxBy

func MaxBy[T any, K constraints.Ordered](slice []T, keyFunc func(T) K) (T, error)

MaxBy returns the element with the maximum key extracted by keyFunc. Returns an error if the slice is empty. MaxBy는 keyFunc으로 추출한 키가 최대인 요소를 반환합니다. 슬라이스가 비어있으면 에러를 반환합니다.

Example 예제:

type Person struct {
    Name string
    Age  int
}
people := []Person{
    {"Alice", 30},
    {"Bob", 25},
    {"Charlie", 35},
}
oldest, _ := sliceutil.MaxBy(people, func(p Person) int {
    return p.Age
}) // {Charlie 35}

func Median

func Median[T Number](slice []T) (float64, error)

Median calculates the median value of a slice of numbers. Returns the middle value for odd-length slices, or the average of the two middle values for even-length slices. Returns an error if the slice is empty.

Median은 숫자 슬라이스의 중앙값을 계산합니다. 홀수 길이 슬라이스의 경우 중간 값을, 짝수 길이 슬라이스의 경우 두 중간 값의 평균을 반환합니다. 슬라이스가 비어 있으면 에러를 반환합니다.

Example:

numbers := []int{3, 1, 4, 1, 5, 9, 2}
median, err := sliceutil.Median(numbers) // 3

evens := []int{1, 2, 3, 4}
median, err := sliceutil.Median(evens) // 2.5

func Min

func Min[T constraints.Ordered](slice []T) (T, error)

Min returns the minimum element in the slice. Returns an error if the slice is empty. Min은 슬라이스의 최소 요소를 반환합니다. 슬라이스가 비어있으면 에러를 반환합니다.

Example 예제:

numbers := []int{3, 1, 4, 1, 5}
min, _ := sliceutil.Min(numbers) // 1

words := []string{"banana", "apple", "cherry"}
min, _ := sliceutil.Min(words) // "apple"

func MinBy

func MinBy[T any, K constraints.Ordered](slice []T, keyFunc func(T) K) (T, error)

MinBy returns the element with the minimum key extracted by keyFunc. Returns an error if the slice is empty. MinBy는 keyFunc으로 추출한 키가 최소인 요소를 반환합니다. 슬라이스가 비어있으면 에러를 반환합니다.

Example 예제:

type Person struct {
    Name string
    Age  int
}
people := []Person{
    {"Alice", 30},
    {"Bob", 25},
    {"Charlie", 35},
}
youngest, _ := sliceutil.MinBy(people, func(p Person) int {
    return p.Age
}) // {Bob 25}

func Mode

func Mode[T comparable](slice []T) (T, error)

Mode returns the most frequently occurring element in the slice. If there are multiple modes, returns the first one encountered. Returns an error if the slice is empty.

Mode는 슬라이스에서 가장 자주 나타나는 요소를 반환합니다. 여러 최빈값이 있는 경우 처음 발견된 것을 반환합니다. 슬라이스가 비어 있으면 에러를 반환합니다.

Example:

numbers := []int{1, 2, 2, 3, 3, 3, 4}
mode, err := sliceutil.Mode(numbers) // 3

func MostCommon

func MostCommon[T comparable](slice []T, n int) []T

MostCommon returns the n most frequently occurring elements in the slice, in descending order of frequency. If there are ties, elements are ordered by their first occurrence in the slice. If n is greater than the number of unique elements, returns all unique elements.

MostCommon은 슬라이스에서 가장 자주 나타나는 n개의 요소를 빈도의 내림차순으로 반환합니다. 동점이 있는 경우 슬라이스에서 처음 나타난 순서대로 정렬됩니다. n이 고유 요소의 수보다 크면 모든 고유 요소를 반환합니다.

Example:

numbers := []int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4}
top2 := sliceutil.MostCommon(numbers, 2) // [4, 3]

func None

func None[T any](slice []T, predicate func(T) bool) bool

None checks if no elements in the slice satisfy the predicate. None은 슬라이스의 어떤 요소도 조건을 만족하지 않는지 확인합니다.

Returns true if no elements satisfy the predicate, false otherwise. 어떤 요소도 조건을 만족하지 않으면 true를, 그렇지 않으면 false를 반환합니다.

An empty slice returns true. 비어있는 슬라이스는 true를 반환합니다.

Example 예제:

numbers := []int{1, 3, 5, 7}
noEven := sliceutil.None(numbers, func(n int) bool { return n%2 == 0 })
// noEven: true

numbers2 := []int{1, 3, 5, 6}
noEven2 := sliceutil.None(numbers2, func(n int) bool { return n%2 == 0 })
// noEven2: false

func Partition

func Partition[T any](slice []T, predicate func(T) bool) ([]T, []T)

Partition splits a slice into two slices based on a predicate. The first slice contains elements that satisfy the predicate. The second slice contains elements that don't satisfy the predicate. Partition은 조건에 따라 슬라이스를 두 개의 슬라이스로 분할합니다. 첫 번째 슬라이스는 조건을 만족하는 요소를 포함합니다. 두 번째 슬라이스는 조건을 만족하지 않는 요소를 포함합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5, 6}
evens, odds := sliceutil.Partition(numbers, func(n int) bool {
    return n%2 == 0
}) // evens: [2, 4, 6], odds: [1, 3, 5]

words := []string{"apple", "a", "banana", "pear", "ab"}
long, short := sliceutil.Partition(words, func(s string) bool {
    return len(s) > 2
}) // long: ["apple", "banana", "pear"], short: ["a", "ab"]

func Percentile

func Percentile[T Number](slice []T, p float64) (float64, error)

Percentile calculates the p-th percentile of a slice of numbers. p should be between 0 and 100 (inclusive). Uses the linear interpolation method. Returns an error if the slice is empty or p is out of range.

Percentile은 숫자 슬라이스의 p번째 백분위수를 계산합니다. p는 0과 100 사이여야 합니다 (포함). 선형 보간법을 사용합니다. 슬라이스가 비어 있거나 p가 범위를 벗어나면 에러를 반환합니다.

Example:

numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
p50, err := sliceutil.Percentile(numbers, 50) // 5.5 (median)
p75, err := sliceutil.Percentile(numbers, 75) // 7.75
p90, err := sliceutil.Percentile(numbers, 90) // 9.1

func Permutations

func Permutations[T any](slice []T) [][]T

Permutations returns all possible permutations of the slice. Returns a slice of slices, where each sub-slice is a permutation. Warning: The number of permutations grows factorially (n!). Permutations는 슬라이스의 모든 가능한 순열을 반환합니다. 각 하위 슬라이스가 순열인 슬라이스의 슬라이스를 반환합니다. 경고: 순열의 수는 팩토리얼로 증가합니다 (n!).

Example 예제:

numbers := []int{1, 2, 3}
perms := sliceutil.Permutations(numbers)
// perms: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]

letters := []string{"a", "b"}
perms := sliceutil.Permutations(letters)
// perms: [["a","b"], ["b","a"]]

Performance note 성능 참고:

n=5: 120 permutations
n=10: 3,628,800 permutations
Use with caution for large slices!

func Reduce

func Reduce[T any, R any](slice []T, initial R, reducer func(R, T) R) R

Reduce applies a reducer function to accumulate a single value from the slice. Reduce는 슬라이스에서 단일 값을 누적하기 위해 reducer 함수를 적용합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
sum := sliceutil.Reduce(numbers, 0, func(acc, n int) int {
    return acc + n
}) // 15

words := []string{"hello", "world"}
combined := sliceutil.Reduce(words, "", func(acc, w string) string {
    return acc + w
}) // "helloworld"

func ReduceRight

func ReduceRight[T any, R any](slice []T, initial R, reducer func(R, T) R) R

ReduceRight applies a reducer function from right to left to accumulate a single value. ReduceRight는 오른쪽에서 왼쪽으로 reducer 함수를 적용하여 단일 값을 누적합니다.

Similar to Reduce, but processes elements from right to left. Reduce와 유사하지만 요소를 오른쪽에서 왼쪽으로 처리합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
result := sliceutil.ReduceRight(numbers, 0, func(acc, n int) int {
    return acc + n
}) // 15 (same as Reduce for commutative operations)

words := []string{"hello", "world"}
combined := sliceutil.ReduceRight(words, "", func(acc, w string) string {
    return acc + w
}) // "worldhello" (reversed compared to Reduce)

// Useful for operations where order matters 순서가 중요한 작업에 유용

nested := [][]int{{1, 2}, {3, 4}, {5}}
flattened := sliceutil.ReduceRight(nested, []int{}, func(acc, slice []int) []int {
    return append(slice, acc...)
}) // [5, 3, 4, 1, 2]

func Remove

func Remove[T any](slice []T, index int) []T

Remove removes the element at the specified index. Remove는 지정된 인덱스의 요소를 제거합니다.

Returns a new slice with the element removed. 요소가 제거된 새 슬라이스를 반환합니다.

If index is out of bounds, returns a copy of the original slice. 인덱스가 범위를 벗어나면 원본 슬라이스의 복사본을 반환합니다.

Example 예제:

slice := []int{1, 2, 3, 4, 5}
result := sliceutil.Remove(slice, 2)

// result: [1, 2, 4, 5] slice: [1, 2, 3, 4, 5] (unchanged 변경되지 않음)

func RemoveAll

func RemoveAll[T comparable](slice []T, item T) []T

RemoveAll removes all occurrences of the specified item. RemoveAll은 지정된 항목의 모든 발생을 제거합니다.

Returns a new slice with all occurrences of the item removed. 항목의 모든 발생이 제거된 새 슬라이스를 반환합니다.

Example 예제:

slice := []int{1, 2, 3, 2, 4, 2, 5}
result := sliceutil.RemoveAll(slice, 2)
// result: [1, 3, 4, 5]

words := []string{"apple", "banana", "apple", "cherry"}
result2 := sliceutil.RemoveAll(words, "apple")
// result2: ["banana", "cherry"]

func RemoveIndices

func RemoveIndices[T any](slice []T, indices []int) []T

RemoveIndices returns a new slice with elements at the specified indices removed. Indices that are out of bounds are silently skipped. Negative indices are not supported and will be skipped. The original slice is not modified.

RemoveIndices는 지정된 인덱스의 요소가 제거된 새 슬라이스를 반환합니다. 범위를 벗어난 인덱스는 자동으로 건너뜁니다. 음수 인덱스는 지원되지 않으며 건너뜁니다. 원본 슬라이스는 수정되지 않습니다.

Example:

numbers := []int{10, 20, 30, 40, 50}
result := sliceutil.RemoveIndices(numbers, []int{1, 3})
// [10, 30, 50] (removed 20 and 40)

// Out of bounds indices are skipped
result := sliceutil.RemoveIndices(numbers, []int{1, 10, 3})
// [10, 30, 50] (index 10 is skipped)

func ReplaceAll

func ReplaceAll[T comparable](slice []T, oldValue, newValue T) []T

ReplaceAll returns a new slice where all occurrences of oldValue are replaced with newValue. The original slice is not modified.

ReplaceAll은 oldValue의 모든 발생을 newValue로 교체한 새 슬라이스를 반환합니다. 원본 슬라이스는 수정되지 않습니다.

Example:

numbers := []int{1, 2, 3, 2, 4, 2}
result := sliceutil.ReplaceAll(numbers, 2, 99)
// [1, 99, 3, 99, 4, 99]

func ReplaceIf

func ReplaceIf[T any](slice []T, predicate func(T) bool, newValue T) []T

ReplaceIf returns a new slice where elements matching the predicate are replaced with newValue. The original slice is not modified.

ReplaceIf는 조건을 만족하는 요소를 newValue로 교체한 새 슬라이스를 반환합니다. 원본 슬라이스는 수정되지 않습니다.

Example:

numbers := []int{1, 2, 3, 4, 5, 6}
result := sliceutil.ReplaceIf(numbers, func(n int) bool {
    return n%2 == 0
}, 0)
// [1, 0, 3, 0, 5, 0] (even numbers replaced with 0)

func Reverse

func Reverse[T any](slice []T) []T

Reverse returns a new slice with elements in reverse order. Reverse는 요소가 역순으로 된 새 슬라이스를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
reversed := sliceutil.Reverse(numbers) // [5, 4, 3, 2, 1]

words := []string{"hello", "world"}
reversed := sliceutil.Reverse(words) // ["world", "hello"]

func RotateLeft

func RotateLeft[T any](slice []T, n int) []T

RotateLeft rotates the slice to the left by n positions. Elements that fall off the left are appended to the right. Returns a new slice, the original is not modified.

RotateLeft는 슬라이스를 왼쪽으로 n 위치만큼 회전합니다. 왼쪽으로 떨어진 요소는 오른쪽에 추가됩니다. 새 슬라이스를 반환하며 원본은 수정되지 않습니다.

Example:

numbers := []int{1, 2, 3, 4, 5}
result := sliceutil.RotateLeft(numbers, 2)
// [3, 4, 5, 1, 2]

// Negative n rotates right
result := sliceutil.RotateLeft(numbers, -1)
// [5, 1, 2, 3, 4]

func RotateRight

func RotateRight[T any](slice []T, n int) []T

RotateRight rotates the slice to the right by n positions. Elements that fall off the right are prepended to the left. Returns a new slice, the original is not modified.

RotateRight는 슬라이스를 오른쪽으로 n 위치만큼 회전합니다. 오른쪽으로 떨어진 요소는 왼쪽에 추가됩니다. 새 슬라이스를 반환하며 원본은 수정되지 않습니다.

Example:

numbers := []int{1, 2, 3, 4, 5}
result := sliceutil.RotateRight(numbers, 2)
// [4, 5, 1, 2, 3]

// Negative n rotates left
result := sliceutil.RotateRight(numbers, -1)
// [2, 3, 4, 5, 1]

func Sample

func Sample[T any](slice []T, n int) []T

Sample returns n random elements from the slice. Elements are selected without replacement (no duplicates). If n is greater than the slice length, returns all elements in random order. Sample은 슬라이스에서 n개의 랜덤 요소를 반환합니다. 요소는 중복 없이 선택됩니다 (복원 추출 없음). n이 슬라이스 길이보다 크면 모든 요소를 랜덤 순서로 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
sample := sliceutil.Sample(numbers, 3) // e.g., [7, 2, 9]

words := []string{"apple", "banana", "cherry", "date"}
sample := sliceutil.Sample(words, 2) // e.g., ["cherry", "apple"]

func Scan

func Scan[T any](slice []T, initial T, accumulator func(T, T) T) []T

Scan returns a slice containing the successive reduced values. It's like Reduce but returns all intermediate results. The first element of the result is always the initial value.

Scan은 연속적인 reduce 값을 포함하는 슬라이스를 반환합니다. Reduce와 비슷하지만 모든 중간 결과를 반환합니다. 결과의 첫 번째 요소는 항상 초기값입니다.

Example:

numbers := []int{1, 2, 3, 4, 5}
result := sliceutil.Scan(numbers, 0, func(acc, n int) int {
    return acc + n
})
// [0, 1, 3, 6, 10, 15] (cumulative sum)

// Running product
result := sliceutil.Scan(numbers, 1, func(acc, n int) int {
    return acc * n
})
// [1, 1, 2, 6, 24, 120] (factorial-like)

func Shuffle

func Shuffle[T any](slice []T) []T

Shuffle returns a new slice with elements in random order. Shuffle은 요소가 무작위 순서로 있는 새 슬라이스를 반환합니다.

Uses a default random source seeded with the current time. 현재 시간으로 시드된 기본 랜덤 소스를 사용합니다.

The original slice is not modified. 원본 슬라이스는 수정되지 않습니다.

Example 예제:

slice := []int{1, 2, 3, 4, 5}

shuffled := sliceutil.Shuffle(slice) shuffled: [3, 1, 5, 2, 4] (random order 무작위 순서) // slice: [1, 2, 3, 4, 5] (unchanged 변경되지 않음)

func Slice

func Slice[T any](slice []T, start, end int) []T

Slice returns a slice of elements from start to end index. Negative indices count from the end of the slice. Slice는 start 인덱스에서 end 인덱스까지의 요소 슬라이스를 반환합니다. 음수 인덱스는 슬라이스 끝에서부터 계산합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
sub := sliceutil.Slice(numbers, 1, 4) // [2, 3, 4]

sub := sliceutil.Slice(numbers, -3, -1) // [3, 4]

func Sort

func Sort[T constraints.Ordered](slice []T) []T

Sort returns a new slice with elements sorted in ascending order. Sort는 오름차순으로 정렬된 요소를 포함하는 새 슬라이스를 반환합니다.

The original slice is not modified. Uses Go's standard sort algorithm. 원본 슬라이스는 수정되지 않습니다. Go의 표준 정렬 알고리즘을 사용합니다.

Example 예제:

numbers := []int{3, 1, 4, 1, 5, 9, 2, 6}
sorted := sliceutil.Sort(numbers)

// sorted: [1, 1, 2, 3, 4, 5, 6, 9] numbers: [3, 1, 4, 1, 5, 9, 2, 6] (unchanged 변경되지 않음)

func SortBy

func SortBy[T any, K constraints.Ordered](slice []T, keyFunc func(T) K) []T

SortBy returns a new slice sorted by the key extracted by keyFunc in ascending order. SortBy는 keyFunc으로 추출한 키를 기준으로 오름차순 정렬된 새 슬라이스를 반환합니다.

The original slice is not modified. The keyFunc extracts a comparable key from each element. 원본 슬라이스는 수정되지 않습니다. keyFunc은 각 요소에서 비교 가능한 키를 추출합니다.

Example 예제:

type Person struct {
    Name string
    Age  int
}
people := []Person{
    {"Alice", 30},
    {"Bob", 25},
    {"Charlie", 35},
}
sortedByAge := sliceutil.SortBy(people, func(p Person) int { return p.Age })
// sortedByAge: [{Bob 25}, {Alice 30}, {Charlie 35}]

func SortByMulti

func SortByMulti[T any](slice []T, less func(i, j T) bool) []T

SortByMulti returns a new slice sorted by using a custom comparison function. SortByMulti는 사용자 정의 비교 함수를 사용하여 정렬된 새 슬라이스를 반환합니다.

The original slice is not modified. The less function should return true if element i should sort before element j. This allows for multi-key sorting by comparing multiple fields. 원본 슬라이스는 수정되지 않습니다. less 함수는 요소 i가 요소 j보다 앞에 정렬되어야 하면 true를 반환해야 합니다. 이를 통해 여러 필드를 비교하여 다중 키 정렬이 가능합니다.

Example 예제:

type Person struct {
    Name string
    Age  int
    Score float64
}
people := []Person{
    {"Alice", 30, 95.5},
    {"Bob", 25, 88.0},
    {"Alice", 25, 92.0},
    {"Bob", 25, 90.0},
}

// Sort by Name (ascending), then Age (ascending), then Score (descending) Name(오름차순), Age(오름차순), Score(내림차순) 순으로 정렬

sorted := sliceutil.SortByMulti(people, func(i, j Person) bool {
    if i.Name != j.Name {
        return i.Name < j.Name
    }
    if i.Age != j.Age {
        return i.Age < j.Age
    }
    return i.Score > j.Score // Descending
})
// sorted: [{Alice 25 92.0}, {Alice 30 95.5}, {Bob 25 90.0}, {Bob 25 88.0}]

func SortDesc

func SortDesc[T constraints.Ordered](slice []T) []T

SortDesc returns a new slice with elements sorted in descending order. SortDesc는 내림차순으로 정렬된 요소를 포함하는 새 슬라이스를 반환합니다.

The original slice is not modified. Uses Go's standard sort algorithm. 원본 슬라이스는 수정되지 않습니다. Go의 표준 정렬 알고리즘을 사용합니다.

Example 예제:

numbers := []int{3, 1, 4, 1, 5, 9, 2, 6}
sorted := sliceutil.SortDesc(numbers)

// sorted: [9, 6, 5, 4, 3, 2, 1, 1] numbers: [3, 1, 4, 1, 5, 9, 2, 6] (unchanged 변경되지 않음)

func StandardDeviation

func StandardDeviation[T Number](slice []T) (float64, error)

StandardDeviation calculates the standard deviation of a slice of numbers. Uses the population standard deviation formula (division by N). Returns an error if the slice is empty.

StandardDeviation은 숫자 슬라이스의 표준 편차를 계산합니다. 모집단 표준 편차 공식을 사용합니다 (N으로 나눔). 슬라이스가 비어 있으면 에러를 반환합니다.

Example:

numbers := []float64{2, 4, 4, 4, 5, 5, 7, 9}
stddev, err := sliceutil.StandardDeviation(numbers) // ~2.0

func Sum

func Sum[T constraints.Integer | constraints.Float](slice []T) T

Sum returns the sum of all elements in the slice. Sum은 슬라이스의 모든 요소의 합을 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
sum := sliceutil.Sum(numbers) // 15

floats := []float64{1.5, 2.5, 3.0}
sum := sliceutil.Sum(floats) // 7.0

func SymmetricDifference

func SymmetricDifference[T comparable](a, b []T) []T

SymmetricDifference returns the symmetric difference of two slices. Elements that are in either a or b, but not in both. SymmetricDifference는 두 슬라이스의 대칭 차집합을 반환합니다. a 또는 b에 있지만 둘 다에 있지 않은 요소.

Example 예제:

a := []int{1, 2, 3, 4}
b := []int{3, 4, 5, 6}
symDiff := sliceutil.SymmetricDifference(a, b) // [1, 2, 5, 6]

words1 := []string{"apple", "banana"}
words2 := []string{"banana", "cherry"}
symDiff := sliceutil.SymmetricDifference(words1, words2) // ["apple", "cherry"]

func Take

func Take[T any](slice []T, n int) []T

Take returns the first n elements from the slice. If n is greater than the slice length, returns the entire slice. Take는 슬라이스에서 첫 n개 요소를 반환합니다. n이 슬라이스 길이보다 크면 전체 슬라이스를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
first3 := sliceutil.Take(numbers, 3) // [1, 2, 3]

words := []string{"hello", "world", "foo"}
first2 := sliceutil.Take(words, 2) // ["hello", "world"]

func TakeLast

func TakeLast[T any](slice []T, n int) []T

TakeLast returns the last n elements from the slice. If n is greater than the slice length, returns the entire slice. TakeLast는 슬라이스에서 마지막 n개 요소를 반환합니다. n이 슬라이스 길이보다 크면 전체 슬라이스를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
last3 := sliceutil.TakeLast(numbers, 3) // [3, 4, 5]

words := []string{"hello", "world", "foo"}
last2 := sliceutil.TakeLast(words, 2) // ["world", "foo"]

func TakeWhile

func TakeWhile[T any](slice []T, predicate func(T) bool) []T

TakeWhile returns elements from the beginning while predicate is true. Stops at the first element that doesn't satisfy the predicate. TakeWhile은 조건이 참인 동안 처음부터 요소를 반환합니다. 조건을 만족하지 않는 첫 번째 요소에서 중지합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 1, 2}
result := sliceutil.TakeWhile(numbers, func(n int) bool {
    return n < 4
}) // [1, 2, 3]

words := []string{"apple", "apricot", "banana", "avocado"}
result := sliceutil.TakeWhile(words, func(s string) bool {
    return len(s) > 0 && s[0] == 'a'
}) // ["apple", "apricot"]

func Tap

func Tap[T any](slice []T, fn func([]T)) []T

Tap executes a function on the slice and returns the slice unchanged. Tap은 슬라이스에 함수를 실행하고 슬라이스를 변경하지 않고 반환합니다.

Useful for debugging or side effects in method chains. 메서드 체인에서 디버깅이나 부수 효과에 유용합니다.

The function receives the entire slice and can perform any operation, but the original slice is returned unchanged. 함수는 전체 슬라이스를 받고 모든 작업을 수행할 수 있지만 원본 슬라이스는 변경되지 않고 반환됩니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
result := sliceutil.Tap(numbers, func(s []int) {
    fmt.Printf("Current slice: %v\n", s)
})
// Output: Current slice: [1 2 3 4 5]
// result: [1, 2, 3, 4, 5]

// Useful in chains 체인에서 유용

result2 := sliceutil.Map(
    sliceutil.Tap(
        sliceutil.Filter(numbers, func(n int) bool { return n%2 == 0 }),
        func(s []int) { fmt.Printf("Filtered: %v\n", s) },
    ),
    func(n int) int { return n * 2 },
)
// Output: Filtered: [2 4]
// result2: [4, 8]

func Union

func Union[T comparable](a, b []T) []T

Union returns the union of two slices (all unique elements from both). Union은 두 슬라이스의 합집합을 반환합니다 (양쪽의 모든 고유 요소).

Example 예제:

a := []int{1, 2, 3}
b := []int{3, 4, 5}
union := sliceutil.Union(a, b) // [1, 2, 3, 4, 5]

words1 := []string{"apple", "banana"}
words2 := []string{"banana", "cherry"}
union := sliceutil.Union(words1, words2) // ["apple", "banana", "cherry"]

func Unique

func Unique[T comparable](slice []T) []T

Unique returns a new slice with duplicate elements removed. Unique는 중복 요소가 제거된 새 슬라이스를 반환합니다.

Example 예제:

numbers := []int{1, 2, 2, 3, 3, 3, 4}
unique := sliceutil.Unique(numbers) // [1, 2, 3, 4]

words := []string{"apple", "banana", "apple", "cherry"}
unique := sliceutil.Unique(words) // ["apple", "banana", "cherry"]

func UniqueBy

func UniqueBy[T any, K comparable](slice []T, keyFunc func(T) K) []T

UniqueBy returns a new slice with duplicate elements removed based on a key function. UniqueBy는 키 함수를 기반으로 중복 요소가 제거된 새 슬라이스를 반환합니다.

Example 예제:

type Person struct {
    Name string
    Age  int
}
people := []Person{
    {"Alice", 25},
    {"Bob", 30},
    {"Alice", 28},
}
unique := sliceutil.UniqueBy(people, func(p Person) string {
    return p.Name
}) // [{"Alice", 25}, {"Bob", 30}]

func Unzip

func Unzip[T, U any](slice [][2]any) ([]T, []U)

Unzip separates a slice of pairs into two slices. Unzip은 쌍의 슬라이스를 두 슬라이스로 분리합니다.

Returns two slices: one with first elements and one with second elements. 두 개의 슬라이스를 반환합니다: 첫 번째 요소를 가진 슬라이스와 두 번째 요소를 가진 슬라이스.

IMPORTANT: Type assertions will panic if the slice contains elements that are not of types T and U. Ensure all pairs are correctly typed before calling this function.

중요: 슬라이스에 T 및 U 타입이 아닌 요소가 포함되어 있으면 타입 단언이 패닉을 발생시킵니다. 이 함수를 호출하기 전에 모든 쌍이 올바르게 타입이 지정되었는지 확인하세요.

Example 예제:

// ✅ CORRECT usage 올바른 사용:

zipped := [][2]any{{1, "one"}, {2, "two"}, {3, "three"}}
numbers, words := sliceutil.Unzip[int, string](zipped)
// numbers: [1, 2, 3]
// words: ["one", "two", "three"]

// ❌ INCORRECT usage (will panic!) 잘못된 사용 (패닉 발생!):

badZipped := [][2]any{{1, "one"}, {"wrong", 2}} // Wrong types 잘못된 타입

nums, words := sliceutil.Unzip[int, string](badZipped) // PANIC!

func UpdateWhere

func UpdateWhere[T any](slice []T, predicate func(T) bool, updater func(T) T) []T

UpdateWhere returns a new slice where elements matching the predicate are updated using the updater function. The original slice is not modified.

UpdateWhere는 조건을 만족하는 요소를 updater 함수로 업데이트한 새 슬라이스를 반환합니다. 원본 슬라이스는 수정되지 않습니다.

Example:

numbers := []int{1, 2, 3, 4, 5}
result := sliceutil.UpdateWhere(numbers,
    func(n int) bool { return n%2 == 0 },
    func(n int) int { return n * 10 })
// [1, 20, 3, 40, 5] (even numbers multiplied by 10)

// Example with structs:
type User struct { ID int; Active bool }
users := []User{{1, false}, {2, true}, {3, false}}
result := sliceutil.UpdateWhere(users,
    func(u User) bool { return !u.Active },
    func(u User) User { u.Active = true; return u })
// All inactive users are now active

func Variance

func Variance[T Number](slice []T) (float64, error)

Variance calculates the variance of a slice of numbers. Uses the population variance formula (division by N). Returns an error if the slice is empty.

Variance는 숫자 슬라이스의 분산을 계산합니다. 모집단 분산 공식을 사용합니다 (N으로 나눔). 슬라이스가 비어 있으면 에러를 반환합니다.

Example:

numbers := []float64{2, 4, 4, 4, 5, 5, 7, 9}
variance, err := sliceutil.Variance(numbers) // 4.0

func Window

func Window[T any](slice []T, size int) [][]T

Window returns a slice of sliding windows of the specified size. Window는 지정된 크기의 슬라이딩 윈도우 슬라이스를 반환합니다.

Returns a slice of slices, where each sub-slice is a window of the specified size. 각 하위 슬라이스가 지정된 크기의 윈도우인 슬라이스의 슬라이스를 반환합니다.

If size is less than or equal to 0, or greater than slice length, returns empty slice. size가 0 이하이거나 슬라이스 길이보다 크면 빈 슬라이스를 반환합니다.

Example 예제:

numbers := []int{1, 2, 3, 4, 5}
windows := sliceutil.Window(numbers, 3)
// windows: [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

words := []string{"a", "b", "c", "d"}
windows2 := sliceutil.Window(words, 2)
// windows2: [["a", "b"], ["b", "c"], ["c", "d"]]

func Zip

func Zip[T, U any](a []T, b []U) [][2]any

Zip combines two slices into a slice of pairs. Zip은 두 슬라이스를 쌍의 슬라이스로 결합합니다.

Returns a slice of [2]any where each element is a pair of elements from the two slices. 각 요소가 두 슬라이스의 요소 쌍인 [2]any의 슬라이스를 반환합니다.

The resulting slice length is the minimum of the two input slices. 결과 슬라이스 길이는 두 입력 슬라이스의 최소값입니다.

Example 예제:

numbers := []int{1, 2, 3}
words := []string{"one", "two", "three"}
zipped := sliceutil.Zip(numbers, words)
// zipped: [[1, "one"], [2, "two"], [3, "three"]]

func ZipWith

func ZipWith[T, U, R any](a []T, b []U, zipper func(T, U) R) []R

ZipWith combines two slices into one using a zipper function. The resulting slice has the length of the shorter input slice.

ZipWith는 zipper 함수를 사용하여 두 슬라이스를 하나로 결합합니다. 결과 슬라이스는 더 짧은 입력 슬라이스의 길이를 가집니다.

Example:

numbers := []int{1, 2, 3}
strings := []string{"a", "b", "c"}
result := sliceutil.ZipWith(numbers, strings, func(n int, s string) string {
    return fmt.Sprintf("%d:%s", n, s)
})
// ["1:a", "2:b", "3:c"]

// Sum corresponding elements
a := []int{1, 2, 3, 4}
b := []int{10, 20, 30}
result := sliceutil.ZipWith(a, b, func(x, y int) int {
    return x + y
})
// [11, 22, 33] (length 3, stops at shorter slice)

Types

type DiffResult

type DiffResult[T any] struct {
	// Elements in new but not in old
	// 새 슬라이스에만 있는 요소
	Added []T
	// Elements in old but not in new
	// 이전 슬라이스에만 있는 요소
	Removed []T
	// Elements in both old and new
	// 양쪽 모두에 있는 요소
	Unchanged []T
}

DiffResult holds the result of a diff operation between two slices. DiffResult는 두 슬라이스 간의 차이 연산 결과를 저장합니다.

func Diff

func Diff[T comparable](old, new []T) DiffResult[T]

Diff compares two slices and returns the differences. Returns elements that were added (in new but not old), removed (in old but not new), and unchanged (in both).

Diff는 두 슬라이스를 비교하여 차이를 반환합니다. 추가된 요소(새 슬라이스에만 있음), 제거된 요소(이전 슬라이스에만 있음), 변경되지 않은 요소(양쪽 모두에 있음)를 반환합니다.

Example:

old := []int{1, 2, 3, 4}
new := []int{2, 3, 4, 5}
diff := sliceutil.Diff(old, new)
// diff.Added: [5]
// diff.Removed: [1]
// diff.Unchanged: [2, 3, 4]

func DiffBy

func DiffBy[T any, K comparable](old, new []T, keyFunc func(T) K) DiffResult[T]

DiffBy compares two slices using a key function and returns the differences. The key function extracts a comparable key from each element for comparison. This is useful for comparing slices of structs or complex types.

DiffBy는 키 함수를 사용하여 두 슬라이스를 비교하고 차이를 반환합니다. 키 함수는 각 요소에서 비교 가능한 키를 추출합니다. 이는 구조체나 복잡한 타입의 슬라이스를 비교할 때 유용합니다.

Example:

type User struct { ID int; Name string }
old := []User{{1, "Alice"}, {2, "Bob"}}
new := []User{{2, "Bob"}, {3, "Charlie"}}
diff := sliceutil.DiffBy(old, new, func(u User) int { return u.ID })
// diff.Added: [{3, "Charlie"}]
// diff.Removed: [{1, "Alice"}]
// diff.Unchanged: [{2, "Bob"}]

type Number

type Number interface {
	constraints.Integer | constraints.Float
}

Number is a constraint for numeric types. Number는 숫자 타입에 대한 제약입니다.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL