Skip to content

Commit 0790158

Browse files
kiramuxgo-interview-practice-bot[bot]coderabbitai[bot]
authored
Add solution for Challenge 30 by kiramux (#726)
* Add solution for Challenge 30 * Update challenge-30/submissions/kiramux/solution-template.go Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: go-interview-practice-bot[bot] <230190823+go-interview-practice-bot[bot]@users.noreply.github.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1 parent 575e2f8 commit 0790158

File tree

1 file changed

+160
-0
lines changed

1 file changed

+160
-0
lines changed
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"time"
7+
)
8+
9+
// ContextManager defines a simplified interface for basic context operations
10+
type ContextManager interface {
11+
// Create a cancellable context from a parent context
12+
CreateCancellableContext(parent context.Context) (context.Context, context.CancelFunc)
13+
14+
// Create a context with timeout
15+
CreateTimeoutContext(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc)
16+
17+
// Add a value to context
18+
AddValue(parent context.Context, key, value interface{}) context.Context
19+
20+
// Get a value from context
21+
GetValue(ctx context.Context, key interface{}) (interface{}, bool)
22+
23+
// Execute a task with context cancellation support
24+
ExecuteWithContext(ctx context.Context, task func() error) error
25+
26+
// Wait for context cancellation or completion
27+
WaitForCompletion(ctx context.Context, duration time.Duration) error
28+
}
29+
30+
// Simple context manager implementation
31+
type simpleContextManager struct{}
32+
33+
// NewContextManager creates a new context manager
34+
func NewContextManager() ContextManager {
35+
return &simpleContextManager{}
36+
}
37+
38+
// CreateCancellableContext creates a cancellable context
39+
func (cm *simpleContextManager) CreateCancellableContext(parent context.Context) (context.Context, context.CancelFunc) {
40+
// DONE: Implement cancellable context creation
41+
// Hint: Use context.WithCancel(parent)
42+
ctx, cancel := context.WithCancel(parent)
43+
return ctx, cancel
44+
}
45+
46+
// CreateTimeoutContext creates a context with timeout
47+
func (cm *simpleContextManager) CreateTimeoutContext(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
48+
// DONE: Implement timeout context creation
49+
// Hint: Use context.WithTimeout(parent, timeout)
50+
ctx, cancel := context.WithTimeout(parent, timeout)
51+
return ctx, cancel
52+
}
53+
54+
// AddValue adds a key-value pair to the context
55+
func (cm *simpleContextManager) AddValue(parent context.Context, key, value interface{}) context.Context {
56+
// DONE: Implement value context creation
57+
// Hint: Use context.WithValue(parent, key, value)
58+
ctx := context.WithValue(parent, key, value)
59+
return ctx
60+
}
61+
62+
// GetValue retrieves a value from the context
63+
func (cm *simpleContextManager) GetValue(ctx context.Context, key interface{}) (interface{}, bool) {
64+
// DONE: Implement value retrieval from context
65+
// Hint: Use ctx.Value(key) and check if it's nil
66+
value := ctx.Value(key)
67+
// Return the value and a boolean indicating if it was found
68+
if value != nil {
69+
return value, true
70+
} else {
71+
return nil, false
72+
}
73+
}
74+
75+
// ExecuteWithContext executes a task that can be cancelled via context
76+
func (cm *simpleContextManager) ExecuteWithContext(ctx context.Context, task func() error) error {
77+
// DONE: Implement task execution with context cancellation
78+
// Hint: Run the task in a goroutine and use select with ctx.Done()
79+
done := make(chan error, 1)
80+
81+
go func() {
82+
done <- task()
83+
}()
84+
85+
// Return context error if cancelled, task error if task fails
86+
select {
87+
case err := <-done:
88+
return err // Task completed first
89+
case <-ctx.Done():
90+
return ctx.Err() // Context cancelled/timeout first
91+
}
92+
}
93+
94+
// WaitForCompletion waits for a duration or until context is cancelled
95+
func (cm *simpleContextManager) WaitForCompletion(ctx context.Context, duration time.Duration) error {
96+
// DONE: Implement waiting with context awareness
97+
// Hint: Use select with ctx.Done() and time.After(duration)
98+
// Return context error if cancelled, nil if duration completes
99+
select {
100+
case <-ctx.Done():
101+
return ctx.Err()
102+
case <-time.After(duration):
103+
return nil
104+
}
105+
}
106+
107+
// Helper function - simulate work that can be cancelled
108+
func SimulateWork(ctx context.Context, workDuration time.Duration, description string) error {
109+
// DONE: Implement cancellable work simulation
110+
// Hint: Use select with ctx.Done() and time.After(workDuration)
111+
// Print progress messages and respect cancellation
112+
select {
113+
case <-ctx.Done():
114+
return ctx.Err()
115+
case <-time.After(workDuration):
116+
fmt.Println(description)
117+
return nil
118+
}
119+
}
120+
121+
// Helper function - process multiple items with context
122+
func ProcessItems(ctx context.Context, items []string) ([]string, error) {
123+
// DONE: Implement batch processing with context awareness
124+
// Process each item but check for cancellation between items
125+
// Return partial results if cancelled
126+
result := make([]string, 0, len(items))
127+
for _, s := range items {
128+
select {
129+
case <-ctx.Done():
130+
return result, ctx.Err()
131+
default:
132+
// The test file's cancellation wait time is too short; a wait time needs to be set.
133+
time.Sleep(30 * time.Millisecond)
134+
processedStr := "processed_" + s
135+
result = append(result, processedStr)
136+
}
137+
}
138+
return result, nil
139+
140+
}
141+
142+
// Example usage
143+
func main() {
144+
fmt.Println("Context Management Challenge")
145+
fmt.Println("Implement the context manager methods!")
146+
147+
// Example of how the context manager should work:
148+
cm := NewContextManager()
149+
150+
// Create a cancellable context
151+
ctx, cancel := cm.CreateCancellableContext(context.Background())
152+
defer cancel()
153+
154+
// Add some values
155+
ctx = cm.AddValue(ctx, "user", "alice")
156+
ctx = cm.AddValue(ctx, "requestID", "12345")
157+
158+
// Use the context
159+
fmt.Println("Context created with values!")
160+
}

0 commit comments

Comments
 (0)