-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathauction_system.go
79 lines (66 loc) · 1.62 KB
/
auction_system.go
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package onlineauctionsystem
import (
"strings"
"sync"
"time"
)
type AuctionSystem struct {
users map[string]*User
auctionListings map[string]*AuctionListing
mu sync.RWMutex
}
var (
instance *AuctionSystem
once sync.Once
)
func GetInstance() *AuctionSystem {
once.Do(func() {
instance = &AuctionSystem{
users: make(map[string]*User),
auctionListings: make(map[string]*AuctionListing),
}
})
return instance
}
func (as *AuctionSystem) RegisterUser(user *User) {
as.mu.Lock()
defer as.mu.Unlock()
as.users[user.ID] = user
}
func (as *AuctionSystem) GetUser(userID string) *User {
as.mu.RLock()
defer as.mu.RUnlock()
return as.users[userID]
}
func (as *AuctionSystem) CreateAuctionListing(listing *AuctionListing) {
as.mu.Lock()
as.auctionListings[listing.ID] = listing
as.mu.Unlock()
// Start auction timer
go func() {
time.Sleep(listing.Duration)
listing.CloseAuction()
}()
}
func (as *AuctionSystem) SearchAuctionListings(keyword string) []*AuctionListing {
as.mu.RLock()
defer as.mu.RUnlock()
var matchingListings []*AuctionListing
keyword = strings.ToLower(keyword)
for _, listing := range as.auctionListings {
if strings.Contains(strings.ToLower(listing.ItemName), keyword) ||
strings.Contains(strings.ToLower(listing.Description), keyword) {
matchingListings = append(matchingListings, listing)
}
}
return matchingListings
}
func (as *AuctionSystem) PlaceBid(auctionListingID string, bid *Bid) bool {
as.mu.RLock()
listing, exists := as.auctionListings[auctionListingID]
as.mu.RUnlock()
if exists {
return listing.PlaceBid(bid)
}
return false
}