npm.io
0.2.4 • Published 2d ago

@cyftec/signal

Licence
MIT
Version
0.2.4
Deps
1
Size
336 kB
Vulns
0
Weekly
0

signal · npm version WIP Tag GitHub license

Signals are basic data units that can automatically alert functions or computations when the data it holds changes. This library is a TypeScript implementation of signals.

The implementation consists of basic building blocks like,
signal - the method to create a source signal of data
derive - the method to create a read-only signal from other signal(s).
effect - the method which takes a callback function, to be run whenever the signals (called inside the callback function's definition), changes

Adding to the project

Currently, only TypeScript and Bun version of the library is completed.
bun add @cyftech/signal

Development Setup

After cloning the repository, set up the git hooks:

bun run setup:hooks

This configures git to use the pre-commit hook in .githooks/ which runs tests before allowing commits.

Usage

import { signal, effect } from "@cyftech/signal";

const color = signal("green");
const TRAFFIC_LIGHT_CHANGE_CUTOFF_IN_MS = 10000;

setInterval(() => {
  if (color.value === "green") color.value = "yellow";
  if (color.value === "yellow") color.value = "red";
  if (color.value === "red") color.value = "green";
}, TRAFFIC_LIGHT_CHANGE_CUTOFF_IN_MS);

// the callback in effect method gets executed every time the value of 'color' signal changes
effect(() => {
  if (color.value === "green")
    updateUiWithMessage("Keep moving. Don't congest the traffic.");

  if (color.value === "yellow")
    updateUiWithMessage("Slow down! Signal is about to stop.");

  if (color.value === "red")
    updateUiWithMessage("STOP. Please do not cross the crossing.");
});

Keywords