Skip to content

harnyk/chan

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

52 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@harnyk/chan - Go channels for TypeScript

This package is my humble attempt to provide a Chan<T> class for TypeScript, which would be as much as possible similar to Go's chan T type.

Installation

npm install @harnyk/chan

Usage

See the tests and examples for more information.

Brief reference:

Go equivalentTypeScript
Create a channel of `number` with no buffer:
ch := make(chan int)
const ch = new Chan<number>();
Create a channel of `number` with fixed-size buffer:
ch := make(chan int, 5)
const ch = new Chan<number>(5);
Iterate over `Chan` with `for await`
for v := range ch {
    fmt.Println(v)
}
for await (const v of ch) {
    console.log(v);
}
Send a value to `Chan` with `send`
ch <- 42
await ch.send(42);
Receive a value from `Chan` with `recv`
v, ok := <-ch
const [v, ok] = await ch.recv();
Close `Chan`
close(ch)
ch.close();
Select over multiple channels
select {
    case ch <- 42:
        fmt.Println("sent")
    case v := <-ch1:
        fmt.Printf("Received %d\n", v)
    default:
        fmt.Println("default")
}
await select()
    .send(ch, 42, () => console.log('sent'))
    .recv(ch1, (v) => console.log(`Received ${v}`))
    .default(() => console.log('default'));

What is supported

  • asynchronous iterating over Chan<T> with for await
  • asynchronous send and recv
  • select-ing over multiple channels

License

WTFPL

Contributors

Mark Harnyk (https://github.com/harnyk)