~telemachus/Exercism

ref: 392885548959505a17ef8731a06b37a972bdd1df Exercism/go/atbash-cipher/atbash_cipher.go.1 -rw-r--r-- 595 bytes
39288554Peter Aronoff Atbash cipher 6 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package atbash

import "strings"

const (
	plain  = "abcdefghijklmnopqrstuvwxyz123456789"
	cipher = "zyxwvutsrqponmlkjihgfedcba123456789"
)

func Atbash(s string) string {
	bs := make([]byte, 0, len(s))
	kept := 0
	s = strings.ToLower(s)

	for _, b := range []byte(s) {
		n := strings.IndexByte(plain, b)
		if n == -1 {
			continue
		}
		// This adds an unwanted space when kept == 0. Trim that off
		// later rather than add a test if keep == 0 to every loop.
		if kept%5 == 0 {
			bs = append(bs, ' ')
		}
		bs = append(bs, cipher[n])
		kept++
	}
	return strings.TrimPrefix(string(bs), " ")
}