The simplest implementation of Golang channels, selects and wait groups

Overview

TypeScript Channels

The simplest implementation of Golang channels, selects and wait groups

Installation

You can use one of the following package managers:

  • Node package manager npm:
npm install channels.ts
  • Yarn package manager yarn:
yarn add channels.ts

How to use it?

Channels

import { Channel, isClosed } from 'channels.ts';

async function main() {
    const chan = new Channel<number>();

    // Closing the channel after 10_000ms
    setTimeout(function() {
        chan.close();
    }, 10_000);

    // Producer routine
    (async function() {
        for (let i = 1; i <= 10; i++) {
            await chan.put(i);
        }
    })();

    // Consumer routine
    (async function() {
        for await (const value of chan) {
            console.log(value);
        }
    })();

    console.log("Waiting for the channel to be closed...");
    await chan.untilClosed();
    console.log("The channel has been closed.");
}

main();

Output:

Waiting for the channel to be closed...
1
2
3
4
5
6
7
8
9
10
The channel has been closed.

First we create a channel of numbers. By default the channel will have a buffer size of 1. Then we define two routines. They are simple IIFE functions that represent the go routines. They are executed immediately and we forget about them. That's why the Waiting for the channel to be closed... message appeared first. Now they can communicate with each other through our channel. The first routine writes to the channel and the second one reads from it. Finally with the chan.untilClosed() we are waiting for the channel to be closed, otherwise the program will exit immediately.

For more details see the documentation.

Select

import { Channel, Select, delay } from "channels.ts";

async function main() {
    const tick = new Channel<number>();
    const boom = new Channel<number>();
    const select = new Select();

    // Puts a value on every 100ms
    const i = setInterval(() => {
        tick.put(0);
    }, 100);

    // Puts a value after 1000ms
    const t = setTimeout(() => {
        boom.put(0);
    }, 1000)

    let b = false;
    while (!b) {
        await select
            .caseTake(tick, async () => console.log("tick."))
            .caseTake(boom, async () => {
                console.log("BOOM!");
                b = true;
            })
            .default(async () => {
                console.log("      .");
                await delay(10);
            })
            .end();
    }

    // Close all channels, intervals and timeouts
    tick.close();
    boom.close();
    clearInterval(i);
    clearTimeout(t);

    console.log("Completed")
}

main();

Wait groups

import { WaitGroup, delay } from "channels.ts";

async function worker(id: number): Promise<void> {
    console.log(`Worker ${id} starting...`);
    await delay(id * 1000);
    console.log(`Worker ${id} done`);
}

async function main() {
    const wg = new WaitGroup();

    for (let i = 1; i <= 5; i++) {
        wg.add(1);

        (async function() {
            await worker(i);
            wg.done();
        })();
    }

    console.log("Waiting...");
    await wg.wait();
    console.log("Done");
}

main();

All examples

You might also like...

This repo has demos, content and documentation of javascript concepts and syntax, in their simplest form. Contribute by sharing your understanding of javascript! Hacktoberfest Accepted!

javascript-documentation open-source hacktoberfest2022 Submit your PR to this javascript-documentation repo 🧭 🌟 ❗ This repo has some of my javascrip

Nov 2, 2022

Displays all hidden Channels, which can't be accessed due to Role Restrictions, this won't allow you to read them (impossible)

Who is the Creator ? The creator of this plugin is DevilBro I have completely reworked the plugin so that it can use the BDFDB library from DevilBro !

Dec 29, 2022

Displays all hidden Channels, which can't be accessed due to Role Restrictions, this won't allow you to read them (impossible)

Displays all hidden Channels, which can't be accessed due to Role Restrictions, this won't allow you to read them (impossible)

ShowHiddenChannels Plugin Returns DevilBro, author of this plugin, and BetterDiscord developers have deleted ShowHiddenChannels plugin from the offici

Sep 17, 2022

Feeds is a simple Revolt bot that delivers RSS feeds to your channels.

Feeds Feeds is a simple Revolt bot that delivers RSS feeds to your text channels. You can invite it here. Feeds are refreshed once per minute, and if

Dec 5, 2022

The simplest way to use AWS/GCP/Azure. From code to cloud in a few minutes.

The simplest way to use AWS/GCP/Azure. From code to cloud in a few minutes.

Utopiops Utopiops is the best way for teams of any size to use cloud (AWS/Azure/GCP), with or without prior experience. We provide a platform that hel

Dec 25, 2022

The simplest yet effective jQuery idle plugin

jquery.inactivity The simplest yet effective jQuery idle (inactivity) plugin Download Uncompressed Compressed Purpose Listen for mouse, keyboard, touc

Oct 18, 2022

This is the simplest possible nodejs api using express.

NodeJS JWT Authentication sample A Todo Application with NodeJS and ExpressJS that uses JWT authentication to manage each user's todos. Available APIs

Sep 11, 2022

Simplest ever I18N 1 KB library for HTML/JavaScript apps.

Simplest ever I18N 1 KB library for HTML/JavaScript apps.

Ultimate I18n JS 🤯 Ultimate internationalization library for web applications. Super simple & easy. Less than 1KB (minified and gziped). 0 dependenci

Dec 22, 2022

A quotaless, partially limitless, and fast Node.js Multiplayer Piano server implementation that efficiently makes use of the protocol and uWebSockets.js

speedymppserver A quotaless, partially limitless, and fast Node.js Multiplayer Piano server implementation that efficiently makes use of the protocol

Oct 14, 2022
Releases(v1.0.1)
Owner
Dimitar Ruskov
Dimitar Ruskov
NAZAR TOOL ON UPDATEING WAIT SOME DAYS

ABOUT TOOL : NAZARi is an information collection tool (OSINT) which aims to carry out Basic Information. It provides various modules that allow effici

MR.NULL666 13 Jun 29, 2022
Demo for my talk "Stream Away the Wait" – a talk about making excellent pending experiences.

?? Stream Away the Wait When implementing the design of a user interface, we often finish before remembering that not everyone's running the app's ser

Kent C. Dodds 25 Nov 1, 2022
This Photoshop script exports all top-level layers and groups to cropped PNG and JPEG files and creates a file usable in Tumult Hype 4 based on your Photoshop document.

Export To Hype (Photoshop Edition) This Photoshop script exports all top-level layers and groups to cropped PNG and JPEG files and creates a file usab

Max Ziebell 6 Nov 9, 2022
A Tailwind plugin that allows to create multiple groups utilities such as group-card or group-1 and works with Tailwind 3 features and all variations.

Tailwind Labeled Groups A plugin that allows to create multiple groups utilities such as group-card or group-1 and works with Tailwind 3 features and

Max 18 Nov 21, 2022
Optimized dracula theme vscode extension for flutter, web, electron and golang development.

Optimized Dracula Theme A color theme inspired by dracula color theme. This color theme is not based on dracula color theme. The color styles are simi

wuchuran 1 Jul 11, 2022
Open-sourced version of Orbis groups.

Documentation: Orbis SDK This example is built using the Orbis SDK that developers can use to created decentralized and composable social applications

Orbis 23 Dec 24, 2022
SSB private groups with ssb-db2

ssb-tribes2 TODO TODO Installation npm install ssb-tribes2 Usage in ssb-db2 Requires Node.js 12 or higher Requires secret-stack@^6.2.0 Requires ssb-db

Secure Scuttlebutt Consortium 5 Dec 15, 2022
sistema de bate ponto para os aprendizes da brisa, usando Angular no frontend, golang no backend e postgresql como banco.

Migule Points Este projeto tem o intuito de automatizar a frequência dos aprendizes da brisanet, usando Angular no front, Golang no backend e postgres

Pedro Miguel 3 Sep 26, 2022
A transpiler from golang's type to typescript's type for collaboration between frontend & backend.

go2type go2type.vercel.app (backup site) A typescript transpiler that convert golang's type to typescript's type. Help front-end developer to work fas

Oanakiaja 8 Sep 26, 2022
App that allows you to control and watch YouTube videos using hand gestures. Additionally, app that allows you to search for videos, playlists, and channels.

YouTube Alternative Interaction App An app I made with Edward Wu that allows you to search and watch videos from YouTube. Leverages Google's YouTube D

Aaron Lam 2 Dec 28, 2021