underscore/init.go
Ruidy 3df26bb95c
feat: add Init function (all but last)
- 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>
2025-11-14 14:50:45 +01:00

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]
}