Skip to content

List Converter — Go source

Transform a list between separators (newline, comma, space, pipe, semicolon, tab) with trim, dedupe, sort, and empty-removal options. Runs entirely in your browser, with a shareable link.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package listconv is the Go twin of CosmoDev's src/lib/list-converter.ts (dual
// source: web lib is TypeScript, CLI lib is Go — kept in lock-step). Pure +
// deterministic, never panics. Table-driven tests share vectors with the TS suite.
package listconv

import (
	"sort"
	"strings"
)

// Separator identifies a built-in list separator. Mirrors the Separator type in
// list-converter.ts. The zero value SepNewline matches the TS "from" default.
type Separator int

const (
	SepNewline Separator = iota
	SepComma
	SepSpace
	SepPipe
	SepSemicolon
	SepTab
)

func sepString(s Separator) string {
	switch s {
	case SepComma:
		return ","
	case SepSpace:
		return " "
	case SepPipe:
		return "|"
	case SepSemicolon:
		return ";"
	case SepTab:
		return "\t"
	default:
		return "\n"
	}
}

// Options mirrors ListOptions in list-converter.ts.
type Options struct {
	From, To                              Separator
	Trim, RemoveEmpty, Unique             bool
	Sort, CaseInsensitive                 bool
}

// Convert transforms a list between separators. Mirrors convertList().
func Convert(input string, opts Options) string {
	items := strings.Split(input, sepString(opts.From))

	if opts.Trim {
		for i := range items {
			items[i] = strings.TrimSpace(items[i])
		}
	}
	if opts.RemoveEmpty {
		filtered := items[:0]
		for _, s := range items {
			if s != "" {
				filtered = append(filtered, s)
			}
		}
		items = filtered
	}
	if opts.Unique {
		seen := make(map[string]bool, len(items))
		filtered := items[:0]
		for _, s := range items {
			k := s
			if opts.CaseInsensitive {
				k = strings.ToLower(s)
			}
			if seen[k] {
				continue
			}
			seen[k] = true
			filtered = append(filtered, s)
		}
		items = filtered
	}
	if opts.Sort {
		sort.SliceStable(items, func(i, j int) bool {
			if opts.CaseInsensitive {
				return strings.ToLower(items[i]) < strings.ToLower(items[j])
			}
			return items[i] < items[j]
		})
	}
	return strings.Join(items, sepString(opts.To))
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →