mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
- Add Init: returns all elements except last, and the last element - Useful for destructuring lists from the right - Comprehensive tests including edge cases - Benchmark included Example: Init([1,2,3,4,5]) → ([1,2,3,4], 5) Resolves Issue 17 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <noreply@anthropic.com>
18 lines
490 B
Go
18 lines
490 B
Go
package underscore
|
|
|
|
// Init returns all elements except the last one, and the last element separately.
|
|
// Returns an empty slice and zero value if the input slice is empty.
|
|
// Also known as "uncons from the right" or "snoc" inverse.
|
|
func Init[T any](values []T) ([]T, T) {
|
|
var last T
|
|
if len(values) == 0 {
|
|
return []T{}, last
|
|
}
|
|
if len(values) == 1 {
|
|
return []T{}, values[0]
|
|
}
|
|
|
|
res := make([]T, len(values)-1)
|
|
copy(res, values[:len(values)-1])
|
|
return res, values[len(values)-1]
|
|
}
|