Created
          June 13, 2011 14:32 
        
      - 
      
 - 
        
Save jeremyBanks/1022871 to your computer and use it in GitHub Desktop.  
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package main | |
| import "fmt" | |
| func MergeChannels(a chan int, b chan int) chan int { | |
| // Merges two channels of sorted ints. | |
| output := make(chan int) | |
| go func() { | |
| defer close(output) | |
| nextA, hasA := <-a | |
| nextB, hasB := <-b | |
| for { | |
| if !(hasA || hasB) { | |
| break | |
| } else if hasA && (!hasB || nextA <= nextB) { | |
| output <- nextA | |
| nextA, hasA = <-a | |
| } else { | |
| output <- nextB | |
| nextB, hasB = <-b | |
| } | |
| } | |
| }() | |
| return output | |
| } | |
| func main() { | |
| a := make(chan int, 5) // ", 5" adds a buffer, otherwise I couldn't just | |
| b := make(chan int, 5) // shove in a bunch of values at once, as below. | |
| merged := MergeChannels(a, b) | |
| a <- 1 | |
| a <- 2 | |
| a <- 4 | |
| a <- 5 | |
| b <- 3 | |
| b <- 4 | |
| b <- 6 | |
| close(a) | |
| close(b) | |
| for value := range merged { | |
| fmt.Print(value, " ") | |
| } | |
| fmt.Print("\n") | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment