{"id":13828964,"url":"https://github.com/lelandmiller/micro-signals","last_synced_at":"2026-04-02T00:41:02.876Z","repository":{"id":44411538,"uuid":"64273199","full_name":"lelandmiller/micro-signals","owner":"lelandmiller","description":"A tiny typed messaging system inspired by js-signals that uses ES2015 sets","archived":false,"fork":false,"pushed_at":"2021-08-10T22:54:03.000Z","size":339,"stargazers_count":40,"open_issues_count":7,"forks_count":7,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-09-24T01:16:32.563Z","etag":null,"topics":["javascript","npm-module","npm-package","pubsub","signal","typescript"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lelandmiller.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-07-27T03:13:15.000Z","updated_at":"2025-03-17T12:40:08.000Z","dependencies_parsed_at":"2022-07-15T10:19:46.655Z","dependency_job_id":null,"html_url":"https://github.com/lelandmiller/micro-signals","commit_stats":null,"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"purl":"pkg:github/lelandmiller/micro-signals","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lelandmiller%2Fmicro-signals","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lelandmiller%2Fmicro-signals/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lelandmiller%2Fmicro-signals/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lelandmiller%2Fmicro-signals/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lelandmiller","download_url":"https://codeload.github.com/lelandmiller/micro-signals/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lelandmiller%2Fmicro-signals/sbom","scorecard":{"id":583749,"data":{"date":"2025-08-11","repo":{"name":"github.com/lelandmiller/micro-signals","commit":"3c893a59c2b2ea2c3e5426c6d9fa915c35e77d4c"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":2.5,"checks":[{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Code-Review","score":6,"reason":"Found 6/10 approved changesets -- score normalized to 6","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Token-Permissions","score":-1,"reason":"No tokens found","details":null,"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Pinned-Dependencies","score":-1,"reason":"no dependencies found","details":null,"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Dangerous-Workflow","score":-1,"reason":"no workflows found","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 26 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":0,"reason":"21 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw","Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92","Warn: Project is vulnerable to: GHSA-v6h2-p8h4-qcjw","Warn: Project is vulnerable to: GHSA-cwfw-4gq5-mrqx","Warn: Project is vulnerable to: GHSA-g95f-p29q-9xw4","Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg","Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275","Warn: Project is vulnerable to: GHSA-765h-qjxv-5f44","Warn: Project is vulnerable to: GHSA-f2jv-r9rf-7988","Warn: Project is vulnerable to: GHSA-43f8-2h32-f4cj","Warn: Project is vulnerable to: GHSA-29mw-wpgm-hmr9","Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm","Warn: Project is vulnerable to: GHSA-4xcv-9jjx-gfj3","Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv","Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3","Warn: Project is vulnerable to: GHSA-vh95-rmgr-6w4m","Warn: Project is vulnerable to: GHSA-xvch-5gv4-984h","Warn: Project is vulnerable to: GHSA-hj48-42vr-x3v9","Warn: Project is vulnerable to: GHSA-6g33-f262-xjp4","Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw","Warn: Project is vulnerable to: GHSA-p9pc-299p-vxgp"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-20T19:52:54.219Z","repository_id":44411538,"created_at":"2025-08-20T19:52:54.219Z","updated_at":"2025-08-20T19:52:54.219Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31293489,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-01T21:15:39.731Z","status":"ssl_error","status_checked_at":"2026-04-01T21:15:34.046Z","response_time":53,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","npm-module","npm-package","pubsub","signal","typescript"],"created_at":"2024-08-04T09:03:23.098Z","updated_at":"2026-04-02T00:41:02.854Z","avatar_url":"https://github.com/lelandmiller.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"![micro-signals](https://rawgit.com/lelandmiller/micro-signals/master/micro-signals.svg)\n\nA tiny typed messaging system inspired by js-signals that uses ES2015 sets\n\n[![Build Status](https://travis-ci.org/lelandmiller/micro-signals.svg?branch=master)](https://travis-ci.org/lelandmiller/micro-signals)\n[![codecov](https://codecov.io/gh/lelandmiller/micro-signals/branch/master/graph/badge.svg)](https://codecov.io/gh/lelandmiller/micro-signals)\n[![The Aj](https://img.shields.io/badge/The_Aj-verified-brightgreen.svg)](https://www.linkedin.com/in/ajay-kodali-1281553/)\n\n## Path to Version 2\n\nVersion 2 of micro-signals will introduce some breaking interface changes. Most notably will be a\nshift from using bindings to a remove method on the signal itself. While bindings were a very nice\ninterface, these changes will allow us to achieve late listener support (memorized signals) in a\nsynchronous signal with a reduced chance for user error.\n\nPreviously, adding late listener support had been put off due to the inability to access the return\nvalue of a listener during the initial cached dispatch of the signal (which would need to happen\nwhile adding the signal). In addition, attempting to use the binding could throw an error during\nthe initial call if the user did not check for the availability of a binding. We considered\nseveral ways around these issues:\n\n1.  Make micro-signals asynchronous\n\n    If a dispatch always calls the listener asynchronously then the binding is always available\n    during the initial call of the listener function, whether a cached value or not. However, some\n    projects may require the use of micro-signals in an environment where asynchronous behavior\n    is not desirable or easy to implement. A synchronous signal still supports asynchronous\n    dispatching (an asynchronous action can be triggered from the listener), but an asynchronous\n    signal does not allow for synchronous action dispatching.\n\n2.  Pass a binding to the listener\n\n    This would ensure that the listener always had a valid reference to the binding. However, the\n    user still needs a way to detach a listener that has not been called yet which, if we\n    continued to use the binding interface, would mean there is still a binding returned from the\n    add function. This could be an easy spot for user error, as forgetting to use the binding\n    passed into a listener would cause the same errors mentioned above.\n\n3.  Do not use bindings\n\n    If we use add and remove methods on signals, we can be sure we are always able to remove during\n    a listener add operation.\n\nSeveral variations of the above were considered, but at the end of it all, option 3 seemed to be the\ncleanest way to provide a synchronous signal with late listener support that avoided the most\nopportunities for user error.\n\nIn order to add some of the convenience of bindings back to the API, there are plans to add the\nability to tag a listener and then remove listeners based on either listener or tags.\n\n## About\n\nmicro-signals is an attempt to provide a simple and flexible signal library for TypeScript and\nJavaScript consumption. It borrows ideas from libraries such as\n[RxJS](https://github.com/Reactive-Extensions/RxJS) and\n[js-signals](https://millermedeiros.github.io/js-signals/).\n\nThe library has no relation to [mini-signals](https://github.com/Hypercubed/mini-signals) and the\nname micro-signals is not meant to imply that this library is smaller than mini-signals in any way.\nThe package was named and published before it was noticed that there already was a mini-signals\nlibrary. Also, it may not seem very \"micro\" at this point. The original implementation was\n[much smaller](https://github.com/lelandmiller/micro-signals/blob/v0.1.0/src/micro-signals.ts) and\nat the time the name made more sense. However, the hope is that this library can provide a very\nuseful signal interface and remain as \"micro\" as possible.\n\n## Usage\n\nInstall using `npm install micro-signals`.\n\n## Signal\n\nSignals allow adding and removing listeners, similar to js-signals, but with methods that can\ncreate new transformed signals (such as map and filter). These methods are similar to the matching\nmethods on a JavaScript array. Each provides a new Signal (it does not modify the current signal)\nand is chainable. All of the Signals described below (MappedSignal, FilteredSignal, etc.) have a\nmatching method on the base Signal.\n\n### Basic Usage of a Signal\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal = new Signal\u003cstring\u003e();\n\nconst received: string[] = [];\n\nconst listener = (payload: string) =\u003e {\n    received.push(payload);\n};\nsignal.add(listener);\n\nsignal.dispatch('a');\n\nsignal.remove(listener);\n\nsignal.dispatch('b');\n\nassert.deepEqual(received, ['a']);\n```\n\n### Using Tags\n\nListeners can also be added and removed with tags. Tags can be provided with the listener to the add\nfunction. If remove is then called with the listener or tag, the listener will be correctly removed.\nAn example might be tagging a listener with an instance of the class from within a class, we can\nthen remove the listener with only the reference to this. This functionality is provided to\npartially mitigate the loss of bindings and the difficulty that keeping track of listeners can pose\nin some cases. However, this interface does not provide the full convenience of bindings. If there\nare any ideas on improvements in this area, suggestions are welcome.\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nclass TestConsumer {\n    receivedPayloads: number[] = [];\n    constructor(private _signal: Signal\u003cnumber\u003e) {\n        this._signal.add(x =\u003e this.receivedPayloads.push(x), this);\n    }\n    detach() {\n        this._signal.remove(this);\n    }\n}\n\nconst signal = new Signal\u003cnumber\u003e();\nconst testConsumer = new TestConsumer(signal);\n\nsignal.dispatch(1);\n\ntestConsumer.detach();\n\nsignal.dispatch(2);\n\nassert.deepEqual(testConsumer.receivedPayloads, [1]);\n```\n\n### Using the Extended Signal Interface\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal = new Signal\u003cstring\u003e();\n\nconst received: string[] = [];\n\nsignal\n    .filter(payload =\u003e payload === 'world')\n    .map(payload =\u003e `hello ${payload}!`)\n    .add(payload =\u003e received.push(payload));\n\nsignal\n    .filter(payload =\u003e payload === 'moon')\n    .map(payload =\u003e `goodnight ${payload}!`)\n    .add(payload =\u003e received.push(payload));\n\nsignal.dispatch('world');\nsignal.dispatch('sun');\nsignal.dispatch('moon');\n\nassert.deepEqual(received, ['hello world!', 'goodnight moon!']);\n```\n\n### Static Methods\n\n#### Signal.merge\n\nSignal.merge takes an arbitrary number of signals as constructor arguments and forward payloads from\nall of the provided signals to the returned signal. This allow multiplexing of Signals. This matches\nthe behavior of the Signal.merge instance method.\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal1 = new Signal\u003cstring\u003e();\nconst signal2 = new Signal\u003cstring\u003e();\n\nconst mergedSignal = Signal.merge(signal1, signal2);\n\nconst received: string[] = [];\n\nmergedSignal.add(payload =\u003e {\n    received.push(payload);\n});\n\nsignal1.dispatch('Hello');\nsignal2.dispatch('world');\nsignal1.dispatch('!');\n\nassert.deepEqual(received, ['Hello', 'world', '!']);\n```\n\n#### Signal.promisify\n\nTurn signals into promises. The first argument is a resolution signal. When the resolution signal is\ndispatched the promise will be resolved with the dispatched value. The second argument is an\noptional rejection signal. When the rejection signal is dispatched the promise will be rejected with\nthe dispatched value. This matches the behavior of the Signal.promisify instance method.\n\n```ts\nimport {Signal} from 'micro-signals';\n\nconst successSignal = new Signal\u003cvoid\u003e();\nconst failureSignal = new Signal\u003cvoid\u003e();\n\nconst promise = Signal.promisify(successSignal, failureSignal);\n\npromise.then(() =\u003e console.log('success')).catch(() =\u003e console.error('failure'));\n```\n\n### Instance Methods\n\n#### Signal.cache\n\nSignal.cache is used to provide late listener support to signals. It takes a cache instance that\nis responsible for determining what values are dispatched to late listeners, and returns a signal\nthat will provide all cached values to new listeners.\n\nThese caches implement a simple interface consisting of an add function to process values\nthat have been dispatched by the base signal and a forEach function to iterate over values that\nshould be provided to late listeners.\n\nTwo basic cache types are provided to cover the most common use cases for cached signals.\nValueCache replays the most recent value (similar to memorize in js-signals) and CollectionCache\nreplays all dispatched values.\n\n```ts\nimport {Signal, ValueCache, CollectionCache} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal = new Signal\u003cstring\u003e();\nconst valueCached = signal.cache(new ValueCache());\nconst collectionCached = signal.cache(new CollectionCache());\n\nconst valueCachedReceived: string[] = [];\nconst collectionCachedReceived: string[] = [];\n\n['a', 'b', 'c'].forEach(payload =\u003e signal.dispatch(payload));\n\nvalueCached.add(payload =\u003e valueCachedReceived.push(payload));\ncollectionCached.add(payload =\u003e collectionCachedReceived.push(payload));\n\n['d', 'e'].forEach(payload =\u003e signal.dispatch(payload));\n\nassert.deepEqual(valueCachedReceived, ['c', 'd', 'e']);\nassert.deepEqual(collectionCachedReceived, ['a', 'b', 'c', 'd', 'e']);\n```\n\nPlease note, there is currently not a way to unbind the cached signal from its base signal. This has\nthe potential to leak attached listeners. In practice this may not be an issue for most use cases.\nMany use cases may have the base signal and the cached signal on the same object. For example:\n\n```ts\nimport {Signal, ValueCache} from 'micro-signals';\nimport * as assert from 'assert';\n\nclass ToggleState {\n    private _stateChanged = new Signal\u003cboolean\u003e();\n    public stateChanged = this._stateChanged.cache(new ValueCache());\n\n    public setState(state: boolean) {\n        this._stateChanged.dispatch(state);\n    }\n}\n\nconst toggleState = new ToggleState();\n\ntoggleState.setState(true);\nlet state = undefined;\ntoggleState.stateChanged.add(toggleState =\u003e state = toggleState);\n\nassert.strictEqual(state, true);\n```\n\nIn this case both signals will become unreachable at the same time, and therefore the base signal\nwill never prevent any cleanup of the cached signal and its context. In many other cases this\nleaking may be negligible as well. However, if this functionality is desired, please file an issue\nor pull request against the repository.\n\n#### Signal.readOnly\n\nreadOnly provides a wrapper around a signal with no dispatch method. This is primarily used to\npublicly expose a signal while indicating that consumers of the signal should not dispatch the\nsignal.\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal = new Signal\u003cstring\u003e();\nconst readOnlySignal = signal.readOnly();\n\nconst received: string[] = [];\n\nreadOnlySignal.add(payload =\u003e {\n    received.push(payload);\n});\n\nassert.equal((readOnlySignal as any).dispatch, undefined);\n\nsignal.dispatch('a');\n\nassert.deepEqual(received, ['a']);\n```\n\n#### Signal.filter\n\nSignal.filter provides the ability to filter values coming through a Signal, similar to filtering an\narray in JavaScript.\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal = new Signal\u003cnumber\u003e();\nconst filteredSignal = signal.filter(x =\u003e x \u003e= 0);\n\nconst received: number[] = [];\n\nfilteredSignal.add(payload =\u003e {\n    received.push(payload);\n});\n\n[-4, 0, 6, -2, 8, 0].forEach(x =\u003e signal.dispatch(x));\n\nassert.deepEqual(received, [0, 6, 8, 0]);\n```\n\nSignal.filter also returns a signal of the correct type when filtering using a type predicate.\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal = new Signal\u003cstring | null\u003e();\nconst filteredSignal = signal.filter((x: string | null): x is string =\u003e typeof x === 'string');\n\nconst received: number[] = [];\n\nfilteredSignal.add(payload =\u003e {\n    // note that the payload type is `string` instead of `string | null`\n    received.push(payload.length);\n});\n\n['1', null, '12', null, '123'].forEach(x =\u003e signal.dispatch(x));\n\nassert.deepEqual(received, [1, 2, 3]);\n```\n\n#### Signal.map\n\nSignal.map provides the ability to transform payloads coming through a Signal, similar to mapping an\narray in JavaScript.\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal = new Signal\u003cstring\u003e();\nconst mappedSignal = signal.map(x =\u003e `${x}!`);\n\nconst received: string[] = [];\n\nmappedSignal.add(payload =\u003e {\n    received.push(payload);\n});\n\n['cat', 'dog', 'frog', 'sloth'].forEach(x =\u003e signal.dispatch(x));\n\nassert.deepEqual(received, ['cat!', 'dog!', 'frog!', 'sloth!']);\n```\n\n#### Signal.peek\n\nPeek allows you to access a payload without consuming it. \n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal = new Signal\u003cstring\u003e();\nconst received: string[] = [];\n\nsignal\n    .map(x =\u003e `${x}!`)\n    .peek(payload =\u003e console.log(payload))\n    .add(payload =\u003e {\n        received.push(payload);\n    });\n\n['cat', 'dog', 'frog', 'sloth'].forEach(x =\u003e signal.dispatch(x));\n\nassert.deepEqual(received, ['cat!', 'dog!', 'frog!', 'sloth!']);\n```\n\n\n#### Signal.reduce\n\nSignal.reduce provides the ability to aggregate payloads coming through a Signal, similar to reducing an array in JavaScript.\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal = new Signal\u003cnumber\u003e();\nconst sumSignal = signal.reduce((total, current) =\u003e total + current, 0);\n\nconst received: number[] = [];\n\nsumSignal.add(payload =\u003e {\n    received.push(payload);\n});\n\n[5, 10, 20, 100].forEach(x =\u003e signal.dispatch(x));\n\nassert.deepEqual(received, [5, 15, 35, 135]);\n```\n\n#### Signal.merge\n\nSignal.merge takes an arbitrary number of signals as constructor arguments and forward payloads from\nall of the provided signals and the base signal. This allow multiplexing of Signals. Effectively it\nmerges the provided signals with the base signal.\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\nconst signal1 = new Signal\u003cstring\u003e();\nconst signal2 = new Signal\u003cstring\u003e();\n\nconst mergedSignal = signal1.merge(signal2);\n\nconst received: string[] = [];\n\nmergedSignal.add(payload =\u003e {\n    received.push(payload);\n});\n\nsignal1.dispatch('Hello');\nsignal2.dispatch('world');\nsignal1.dispatch('!');\n\nassert.deepEqual(received, ['Hello', 'world', '!']);\n```\n\n#### Signal.promisify\n\nTurn signals into promises. The base signal is a resolution signal. When the resolution signal is\ndispatched the promise will be resolved with the dispatched value. The second argument is an\noptional rejection signal. When the rejection signal is dispatched the promise will be rejected with\nthe dispatched value.\n\n```ts\nimport {Signal} from 'micro-signals';\n\nconst successSignal = new Signal\u003cvoid\u003e();\nconst failureSignal = new Signal\u003cvoid\u003e();\n\nconst promise = successSignal.promisify(failureSignal);\n\npromise.then(() =\u003e console.log('success')).catch(() =\u003e console.error('failure'));\n```\n\n### ExtendedSignal\n\nAn ExtendedSignal class is provided for the creation of a custom signal or wrapping a basic signal\n(containing only an add method) with the remainder of the methods found on a micro-signals Signal\n(such as map, filter, and so on). In many cases this gives us an easy way to ensure an intermediate\nSignal does not block garbage collection, and in some cases may present a simpler way to obtain a\ndesired interface. For example, this makes it possible to extend the ExtendedSignal class to get the\nSignal interface without having to expose the add method anywhere.\n\nCompare the following code examples:\n\n```ts\nimport {ExtendedSignal} from 'micro-signals';\nimport EventEmitter = require('events');\nimport * as assert from 'assert';\n\nconst emitter = new EventEmitter();\n\nconst signal = new ExtendedSignal\u003cnumber\u003e({\n    add(listener) {\n        emitter.on('event', listener);\n    },\n    remove(listener) {\n        emitter.removeListener('event', listener);\n    },\n});\n\nconst received: number[] = [];\n\nsignal.map(x =\u003e x + 1).add(payload =\u003e received.push(payload));\n\nemitter.emit('event', 1);\nemitter.emit('event', 2);\n\nassert.deepEqual(received, [2, 3]);\n```\n\n```ts\nimport {Signal} from 'micro-signals';\nimport EventEmitter = require('events');\nimport * as assert from 'assert';\n\nconst emitter = new EventEmitter();\n\nconst signal = new Signal\u003cnumber\u003e();\n\nemitter.on('event', payload =\u003e signal.dispatch(payload));\n\nconst received: number[] = [];\n\nsignal.map(x =\u003e x + 1).add(payload =\u003e received.push(payload));\n\nemitter.emit('event', 1);\nemitter.emit('event', 2);\n\nassert.deepEqual(received, [2, 3]);\n```\n\nThough the second is more terse, there is always a listener connected to the underlying emitter\nobject. In some cases this may prevent proper garbage collection. In the top example, the Signal\nonly acts as a transformation layer, transforming listeners to provide the interface of a Signal\nwithout storing any state itself. This is how the internal signal transformations work in order to\nremove unnecessary intermediate signals. Feel free to use or ignore the ExtendedSignal at your\ndiscretion.\n\n### Default Listeners\n\nDefault listeners allow the signal owner to define some default\naction that should be taken when a signal is dispatched but no\nlisteners have been added. Typically this would be used to throw\nor log an error if no listeners are present for an important signal.\n\nDefault listeners can be set with either the static \nsetDefaultListener method or the instance setDefaultListener method.\n\nThe static default listener will be called on any signal that has\nno listeners present (even if no instance default listener is set).\n\nThe instance default listener will only be called when the \nspecific signal instance is dispatched with no listeners present.\n\n\n\n```ts\nimport {Signal} from 'micro-signals';\nimport * as assert from 'assert';\n\n// static default listener\nconst staticPayloads: string[] = [];\nconst signal = new Signal\u003cstring\u003e();\n\nSignal.setDefaultListener(payload =\u003e staticPayloads.push(payload));\n\nsignal.dispatch('hello static listener');\n\nassert.equal(staticPayloads.length, 1);\nassert.equal(staticPayloads[0], 'hello static listener');\n\n// instance default listener\nconst instancePayloads: string[] = [];\nsignal.setDefaultListener(payload =\u003e instancePayloads.push(payload));\n\nsignal.dispatch('hello instance listener');\n\n// static default listener is not used once instance default listener has been set.\nassert.equal(staticPayloads.length, 1);\nassert.equal(instancePayloads.length, 1);\nassert.equal(instancePayloads[0], 'hello instance listener');\n```\n\n\n### Interfaces\n\nSeveral interfaces are exported as well for convenience:\n\n-   Listener is an interface that defines a function that can be passed to Signal methods taking a\n    listener (such as add or addOnce).\n-   ReadableSignal is an interface for a Signal without dispatch.\n-   WritableSignal only defines the dispatch method.\n\n```ts\nimport {Signal, Listener, ReadableSignal, WritableSignal} from 'micro-signals';\n\nconst listener: Listener\u003cstring\u003e = payload =\u003e console.log(payload);\n\nconst signal = new Signal\u003cstring\u003e();\n\n// A ReadableSignal cannot be dispatched\nconst readable: ReadableSignal\u003cstring\u003e = signal;\n\nreadable.add(listener);\n\n// A WritableSignal can be dispatched\nconst writable: WritableSignal\u003cstring\u003e = signal;\n\nwritable.dispatch('hello!');\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flelandmiller%2Fmicro-signals","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flelandmiller%2Fmicro-signals","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flelandmiller%2Fmicro-signals/lists"}