protohackers/cmd/budgetchat/room.go

60 lines
924 B
Go

package main
import (
"fmt"
"strings"
)
type room struct {
users []*user
}
func createRoom() *room {
return &room{
users: make([]*user, 16),
}
}
func (r *room) joinUser(u *user) {
for _, usr := range r.users {
if usr.nick == u.nick {
}
}
r.users = append(r.users, u)
u.online = true
}
func (r *room) sendToAll(msg string) {
for _, u := range r.users {
if u.online {
u.write(msg)
}
}
}
func (r *room) sendToRest(msg string, skip *user) {
for _, u := range r.users {
if u.online && u != skip {
u.write(msg)
}
}
}
func (r *room) connected() (nicks []string) {
for _, u := range r.users {
if u.online {
nicks = append(nicks, u.nick)
}
}
return nicks
}
func (r *room) joinMsg(u *user) string {
return fmt.Sprintf("* %s has joined the channel", u.nick)
}
func (r *room) connectMsg() string {
return fmt.Sprintf("* The room contains: %s", strings.Join(r.connected(), ", "))
}