diff --git a/secret_handshake.go b/secret_handshake.go index a99f030..592c62a 100644 --- a/secret_handshake.go +++ b/secret_handshake.go @@ -13,29 +13,25 @@ const ( // Handshake receives an integer argument and returns a string slice with // the code words in the proper sequence. func Handshake(i int) (h []string) { - // Store the handshake phrases in a string slice (maps are slow). - s := []string{"wink", "double blink", "close your eyes", "jump"} - // Return the original nil slice if the integer is negative. if i < 0 { return h } - // Build the slice by bitmasking the integer. - if i&wnk != 0 { - h = append(h, s[0]) - } - if i&bli != 0 { - h = append(h, s[1]) - } - if i&clo != 0 { - h = append(h, s[2]) - } - if i&jmp != 0 { - h = append(h, s[3]) + // Store the handshake phrases in a string slice (maps are slow). + s := []string{"wink", "double blink", "close your eyes", "jump"} + + // Define an ordered set of keys. + keys := []int{wnk, bli, clo, jmp} + + // Build the string slice by bitmasking the integer. + for n, k := range keys { + if i&k != 0 { + h = append(h, s[n]) + } } - // Reverse the slice if the 5th bit is set. + // Reverse the slice (in-place) if the 5th bit is set. if i&rev != 0 { for i, j := 0, len(h)-1; i < j; i, j = i+1, j-1 { h[i], h[j] = h[j], h[i] @@ -45,7 +41,7 @@ func Handshake(i int) (h []string) { return h } -// Revision 1 benchmark: +// Revision 2 benchmark: // // PASS -// BenchmarkHandshake-12 5000000 334 ns/op +// BenchmarkHandshake-12 5000000 338 ns/op