Skip to content

Commit 782f3c4

Browse files
Add solution for Challenge 30 by ashwinipatankar (#165)
1 parent 9d2803f commit 782f3c4

File tree

1 file changed

+163
-0
lines changed

1 file changed

+163
-0
lines changed
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
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+
// TODO: Implement cancellable context creation
41+
// Hint: Use context.WithCancel(parent)
42+
return context.WithCancel(parent)
43+
}
44+
45+
// CreateTimeoutContext creates a context with timeout
46+
func (cm *simpleContextManager) CreateTimeoutContext(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
47+
// TODO: Implement timeout context creation
48+
// Hint: Use context.WithTimeout(parent, timeout)
49+
return context.WithTimeout(parent, timeout)
50+
}
51+
52+
// AddValue adds a key-value pair to the context
53+
func (cm *simpleContextManager) AddValue(parent context.Context, key, value interface{}) context.Context {
54+
// TODO: Implement value context creation
55+
// Hint: Use context.WithValue(parent, key, value)
56+
return context.WithValue(parent, key, value)
57+
}
58+
59+
// GetValue retrieves a value from the context
60+
func (cm *simpleContextManager) GetValue(ctx context.Context, key interface{}) (interface{}, bool) {
61+
// TODO: Implement value retrieval from context
62+
// Hint: Use ctx.Value(key) and check if it's nil
63+
// Return the value and a boolean indicating if it was found
64+
val := ctx.Value(key)
65+
if val == nil {
66+
return nil, false
67+
}
68+
69+
return val, true
70+
}
71+
72+
// ExecuteWithContext executes a task that can be cancelled via context
73+
func (cm *simpleContextManager) ExecuteWithContext(ctx context.Context, task func() error) error {
74+
// TODO: Implement task execution with context cancellation
75+
// Hint: Run the task in a goroutine and use select with ctx.Done()
76+
// Return context error if cancelled, task error if task fails
77+
done := make(chan error, 1)
78+
79+
go func() {
80+
done <- task()
81+
}()
82+
83+
select {
84+
case err := <-done:
85+
return err // Task completed first
86+
case <-ctx.Done():
87+
return ctx.Err() // Context cancelled/timeout first
88+
}
89+
}
90+
91+
// WaitForCompletion waits for a duration or until context is cancelled
92+
func (cm *simpleContextManager) WaitForCompletion(ctx context.Context, duration time.Duration) error {
93+
// TODO: Implement waiting with context awareness
94+
// Hint: Use select with ctx.Done() and time.After(duration)
95+
// Return context error if cancelled, nil if duration completes
96+
97+
select {
98+
case <-ctx.Done():
99+
// work cancelled
100+
return ctx.Err()
101+
case <-time.After(duration):
102+
// work completed
103+
return nil
104+
}
105+
106+
}
107+
108+
// Helper function - simulate work that can be cancelled
109+
func SimulateWork(ctx context.Context, workDuration time.Duration, description string) error {
110+
// TODO: Implement cancellable work simulation
111+
// Hint: Use select with ctx.Done() and time.After(workDuration)
112+
// Print progress messages and respect cancellation
113+
select {
114+
case <-ctx.Done():
115+
// work cancelled
116+
return ctx.Err()
117+
case <-time.After(workDuration):
118+
// work completed
119+
return nil
120+
}
121+
122+
}
123+
124+
// Helper function - process multiple items with context
125+
func ProcessItems(ctx context.Context, items []string) ([]string, error) {
126+
// TODO: Implement batch processing with context awareness
127+
// Process each item but check for cancellation between items
128+
// Return partial results if cancelled
129+
var newItems []string
130+
for i := range items {
131+
select {
132+
case <-ctx.Done():
133+
return newItems, ctx.Err()
134+
default:
135+
// Process item
136+
}
137+
138+
time.Sleep(100 * time.Millisecond)
139+
newItems = append(newItems, fmt.Sprintf("processed_%v", items[i]))
140+
}
141+
142+
return newItems, nil
143+
}
144+
145+
// Example usage
146+
func main() {
147+
fmt.Println("Context Management Challenge")
148+
fmt.Println("Implement the context manager methods!")
149+
150+
// Example of how the context manager should work:
151+
cm := NewContextManager()
152+
153+
// Create a cancellable context
154+
ctx, cancel := cm.CreateCancellableContext(context.Background())
155+
defer cancel()
156+
157+
// Add some values
158+
ctx = cm.AddValue(ctx, "user", "alice")
159+
ctx = cm.AddValue(ctx, "requestID", "12345")
160+
161+
// Use the context
162+
fmt.Println("Context created with values!")
163+
}

0 commit comments

Comments
 (0)