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

algebraic-type

v1.1.0

Published

Algebraic data types for JavaScript (which works with plain object) for use with Redux

Downloads

1,096

Readme

algebraic-type

Algebraic types for JavaScript. Inspired by adt and the Elm architecture, but works with plain object.

Why?

To reduce boilerplate in generating and checking Redux action objects. To reduce errors when creating Redux action types and reducers. To allow action’s shape to be specified.

Examples

import AlgebraicType from 'algebraic-type'

Simple Example

type Action = Increment | Decrement
const Action = AlgebraicType({
  Increment: { },
  Decrement: { },
})

Todo Example from Redux

  • The Flux/Redux approach is to define action types as string constants. Each action type name is spelled out twice. There is a possibility that the constant or the value is misspelled.

    export const ADD_TODO = 'ADD_TODO'
    export const DELETE_TODO = 'DELETE_TODO'
    export const EDIT_TODO = 'EDIT_TODO'
    export const COMPLETE_TODO = 'COMPLETE_TODO'
    export const COMPLETE_ALL = 'COMPLETE_ALL'
    export const CLEAR_COMPLETED = 'CLEAR_COMPLETED'
  • In Elm, you declare your action as an algebraic data type. This also lets you specify the shape of your action, as well as providing type safety.

    type Action
        = AddTodo String
        | DeleteTodo Int
        | EditTodo Int String
        | CompleteTodo Int
        | CompleteAll
        | ClearCompleted
  • With algebraic-type, you create an algebraic type like this. Each key is the action type’s name. Inside it, you describe the shape of the object.

    const Action = AlgebraicType({
      AddTodo: {
        text: String,
      },
      DeleteTodo: {
        id: Number,
      },
      EditTodo: {
        id: Number,
        text: String,
      },
      CompleteTodo: {
        id: Number,
      },
      CompleteAll: { },
      ClearCompleted: { },
    })

    You still have the benefit of seeing all the actions in your application in a single place.

  • Plain Redux Action Creators: Create an object literal directly.

    export function addTodo(text) {
      return { type: types.ADD_TODO, text }
    }

    There is a possibility that you misspelt the property name. Maybe it’s late at night and you’re hungry and thinking about some tofu soup. You typed in types.ADD_TOFU (or just ADD_TOFU in case of ES6 imports). You end up dispatching an undefined action. You may also be dispatching a malformed object.

  • With algebraic-type: You invoke the value constructor.

    function addTodo(text) {
      return Action.AddTodo({ text })
    }

    The value constructor validates what’s passed into it, and returns a plain, serializable object with the type property set to the constructor’s name.

    Action.AddTodo({ text: 'Learn Redux' })
    // => { type: 'AddTodo', text: 'Learn Redux' }

    You immediately get an error if you misspell it.

    Action.AddTofu({ text: 'Learn Redux' })
    // => TypeError: Action.AddTofu is not a function

    You immediately get an error if it is not in the shape you specified.

    Action.AddTodo({ task: 'Learn Redux' })
    // => Error: missing property: "text"

    algebraic-type is not a replacement for action creators; they are simply utilities that helps you creating well-formed action types and action objects. The case for action creators still holds.

  • Plain Redux: Use switch statements. If you misspeelt the imported name, your reducer simply won’t process the action.

    export default function todos(state = initialState, action) {
      switch (action.type) {
        case ADD_TODO:
          ...
    
        case DELETE_TODO:
          ...
    
        default:
          return state
      }
    }
  • With algebraic-type: Use the generated matcher function. If you misspelt the action name, you immediately get a TypeError.

    export default function todos(state = initialState, action) {
      if (Action.isAddTodo(action)) {
        ...
      }
      else if (Action.isDeleteTodo(action)) {
        ...
      }
      else {
        return state
      }
    }
  • TK createReducer example.

Moar Feature Ideas

These are just ideas; they are not implemented yet.

  • Add name prefix to generated type to prevent them from clashing. Maybe follow the ducks convention:

    const Action = AlgebraicType({
      prefix: 'my-app/widgets/',
      Load: { },
      Create: { widget: Object },
      Update: { widget: Object },
      Remove: { widget: Object },
    })

    Another example is to construct similar-looking actions:

    function AsyncAction(prefix) {
      return new AlgebraicType({
        prefix,
        Request: { },
        Success: { response: Object },
        Failure: { error: String },
      })
    }
  • Allow type composition/nested actions. This allows actions to be more modular.

    Here is an example from Elm’s architecture tutorial, a list of counters:

    import { Action as CounterAction } from './counter'
    
    const Action = AlgebraicType({
      prefix: 'my-app/main/',
      Insert: { },
      Remove: { },
      Modify: { id: String, action: CounterAction },
    })
  • switch() function that takes an incoming object and switches between functions based on type.

  • types() function that returns an list of available keys.