npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

typesafe-reducer

v1.0.4

Published

A TypeScript library that helps create type-safe dispatcher and reducer functions

Downloads

461

Readme

typesafe-reducer

A TypeScript library that helps create type-safe dispatcher and reducer functions

In order to use this library, you should have some familiarity with Typescript ADTs

Installation

Install the package:

npm install typesafe-reducer

Import it into your script:

import { generateReducer, State, Action } from 'typesafe-reducer';

Usage

// Let's imagine that our application can have two states
// (`MainState` and `LoadingState`). We would create an interface for each
// state, with a `type` property that is going to be used to
// discriminate between the states:
type LoadingState = State<'LoadingState', {
  readonly task: Promise<string[]>;
}>;
type MainState = State<'MainState', {
  readonly data: string[];
}>;

// And we should create a type called `states` that would combine all
// of the states our application has
type States =
  | LoadingState;
  | MainState;

// Let's do something similar for all the possible actions:
type LoadedAction = Action<'LoadedAction', {
  readonly data: string[];
}>;
type BeginLoadingAction = Action<'BeginLoadingAction'>;

type Actions =
  | LoadedAction
  | BeginLoadingAction;

// Now we can create the reducer:
// Notice how we supply state and action types in `<States, Actions>`
const reducer = generateReducer<States, Actions>({`
  'LoadedAction':({state, action})=>{
    return {
      type: 'MainState',
      data: action.data,
    };
  },
  'BeginLoadingAction':({state, action})=>{
    return {
      type: 'LoadingState',
      task: new Promise((resolve)=>
        setTimeout(()=>{
          resolve(['test','test','test']);
        },1000);
      );
    };
  }
});

// Now, you can use React's useReducer like this:
// https://github.com/specify/specify7/blob/90d80aae15ddbb588ea3fe556be3538db5e19483/specifyweb/frontend/js_src/lib/components/wbplanview.tsx#L84
// Or create your own dispatch:
const dispatch = (state:states,action:actions)=>{
  const newState = reducer(state,action);

  //handle setState here
  console.log(newState);
}

// After that, you can call the dispatch function from anywhere and
// provide the necessary arguments (`currentState` state is the
// current state of the application)
window.addEventListener('click', ()=>
  dispatch(
    currentState,
    {
      type: 'InitializeLoadingAction',
    }
  )
);

// Alternatively, you may want to mutate the current state inside of
// the reducer (though, be careful with it as side effects are
// dangerous)
let state:State1 = {
  type: 'State1',
  field: 'qwerty',
}
const dispatch = generateDispatch<actions>({
  'Action1':(action)=>{
    state = { // mutate the external state
      ...state,
      type: 'State2',
      is: true,
    }
    console.log(state,action);
  },
  'Action2':(action)=>{
    //mutate the external state here
  }
});

Advanced Usage

// There is a functionality to limit certain action calls only to some
// events. If action is called from a wrong event, an exception is
// triggered.
// To implement this, wrap reducer handler in an ensureState function,
// where first argument is an array of allowed types and second argument
// is the handler. Example:

const reducer = generateReducer<States, Actions>({`
  // Only allow calling LoadedAction from LoadingState
  'LoadedAction': ensureState(['LoadingState'],({state, action})=>{
    return {
      type: 'MainState',
      data: action.data,
    };
  }),
  'BeginLoadingAction': ensureState(['MainState'],({state, action})=>{
    return {
      type: 'LoadingState',
      task: new Promise((resolve)=>
        setTimeout(()=>{
          resolve(['test','test','test']);
        },1000);
      );
    };
  })
});

Credit

Some code was based on babakness/exhaustive-type-checking