call-context
TypeScript icon, indicating that this package has built-in type declarations

0.4.0 • Public • Published

This package provides a simple call-stack context provision.

Usage

import { context } from "call-context";
 
const ctx = context("my context"); // name is optional
const fn = () => {
  console.log(ctx.require()); // we'll provide 42, so this will log 42.
};
 
const contextProvidedFn = ctx.provide(42)(fn);
contextProvidedFn();

Context's require() will throw an error if the context has not been provided. Name your context at construction time so that you get a meaningful error message.

Providing several contexts

Use provide.

import { provide } from "call-context";
 
const contextProvidedFn =
  provide(context1, value1)(context2, value2)(context3, value3)(fn);

Optional provision

Use get to consume the context optionally. This returns undefined if the context has not been provided.

import { context } from "call-context";
 
const ctx = context("my context"); // name is optional
const fn = () => {
  console.log(ctx.get() ?? 42); // This will log 42 without provision.
};
fn();

Use cases

Using call-stack context allows dependencies to be provided deep in the call hierarchy. This idea is inspired from React's conext, which allows dependencies to be provided deep in the component hierarchy. Context allows for more liberal use of dependency inversion, because it reduces the amount of pumbling required to send the dependencies to the use site.

The alternative, i.e. passing dependencies down the call hierarchy, has better traceability.

Package Sidebar

Install

npm i call-context

Weekly Downloads

0

Version

0.4.0

License

none

Unpacked Size

10.5 kB

Total Files

24

Last publish

Collaborators

  • soul-codes