Sha256: f9aa1387bfd176f93ab786b3a72b640ce59e325dcad42ebf6ed0de9d9fc4421f

Contents?: true

Size: 1.37 KB

Versions: 121

Compression:

Stored size: 1.37 KB

Contents

package cipher

import "strings"

func NewCaesar() Cipher { return NewShift(3) }

type shift int

func NewShift(s int) Cipher {
	c := shift(s)
	switch {
	case c > 0 && c < 26:
		return c
	case c > -26 && c < 0:
		c += 26
		return c
	}
	return nil
}

func (c shift) Encode(s string) string {
	return strings.Map(
		func(r rune) rune { return enc(r, int(c)) },
		s)
}

func (c shift) Decode(ct string) string {
	return strings.Map(
		func(r rune) rune { return dec(r, int(c)) },
		ct)
}

func enc(r rune, sa int) rune {
	switch {
	case r >= 'a' && r <= 'z':
		return (r-'a'+rune(sa))%26 + 'a'
	case r >= 'A' && r <= 'Z':
		return (r-'A'+rune(sa))%26 + 'a'
	}
	return -1
}

func dec(r rune, sa int) rune {
	if r >= 'a' && r <= 'z' {
		return (r-'a'+rune(26-sa))%26 + 'a'
	}
	return -1
}

type vigenere string

func NewVigenere(key string) Cipher {
	ok := false
	for _, r := range key {
		switch {
		case r < 'a' || r > 'z':
			return nil
		case r > 'a':
			ok = true
		}
	}
	if !ok {
		return nil
	}
	return vigenere(key)
}

func (v vigenere) Encode(s string) string {
	x := 0
	return strings.Map(
		func(r rune) rune {
			if r = enc(r, int(v[x]-'a')); r >= 0 {
				x = (x + 1) % len(v)
			}
			return r
		},
		s)
}

func (v vigenere) Decode(ct string) string {
	x := 0
	return strings.Map(
		func(r rune) rune {
			if r = dec(r, int(v[x]-'a')); r >= 0 {
				x = (x + 1) % len(v)
			}
			return r
		},
		ct)
}

Version data entries

121 entries across 121 versions & 1 rubygems

Version Path
trackler-2.0.8.20 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.19 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.18 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.17 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.16 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.15 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.14 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.13 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.12 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.11 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.10 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.9 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.8 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.7 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.6 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.5 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.4 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.3 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.2 tracks/go/exercises/simple-cipher/example.go
trackler-2.0.8.1 tracks/go/exercises/simple-cipher/example.go