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

@playframe/statue

v1.0.4

Published

Art of State Management

Downloads

1

Readme

PlayFrame

Statue

0.4 kb Art of functional State

Installation

npm install --save @playframe/statue

Description

Statue is a Redux like functional state manegement library that lets you define and access actions right inside of your state. So you could describe a deeply nested state tree with nested actions in one simple object.

To update state, action could return a new object that has one or more properties. This will produce a new state with those properties updated.

Another option is to mutate a state object passed to your function. Mutation will be detected and this will produce a new state as well. Returned value is ignored in this case. If you are writing a performance demanding reducer, please use this mutation trick and define the hottest property as the first one in your initial state for faster checking.

If you don't want to update state, please make sure you action returns something falsy or the same state that was passed to it

To work with state directly you can do

// to update the state
state._(updated)

// to read the latest state
state = state._()

// to turn a function into a reducer
state._.new_action = state._( (x, state)=> state.x = x )

Statue also cares not to send too many updates from child to parent branches

Usage

import statue from '@playframe/statue'
const state = statue({
  i: 0,
  _: {
    increment: (x, state)=> i: state.i + 1,
    incrementBy: (n)=>(event, state)=> state.i += n // mutating
  },
  subState: {
    i: 0,
    _: {
      increment: (x, state)=> i: state.i + 1
    }
  }
  },
  setTimeout,
  (newState)=> {
    console.log('Counter is:', newState.i)
    console.log('Subcounter is:', newState.subState.i)
  }
)
for(let j = 0; j < 100; j++){
  state.subState._.increment()
  state.subState._.increment()
  state._.increment()
}
// Logs only once
//> Counter is: 100
//> Subcounter is: 200
// Will increment by 10 and log in console on every click
$('button').click( state._.incrementBy(10) )

Annotated Source

Caching static functions from Object

{assign, create, keys} = Object

is_function = (f)=>
  typeof f is 'function'

Let's define a function that takes a takes state_actions as an initial state and its reducers (actions) defined under _ (underscore) property. Our function also takes level_up or 'subscribe' function that will be called when state updates. Most sertainly we don't want to update the whole state tree every time nested leaf updates, so we also pass a delayed function that will help debounce parent update

module.exports = statue = (state_actions, delayed, level_up)=>
###                       state._.actions
                               ]_[.state._.actions
                               [_]      ]_[.
                               [_]      [_]
###
  actions = state_actions._
  _state = state_actions # _closure
  _scheduled = false # _closure
  _nested = reset = => _nested = reset # reset _nested


  # delaying child state updates
  delay_nested = (f)=>
    _nested = do (_nested)=>=> do _nested; do f; return
    do schedule
    return


  # recursive statue if there nested actions
  for k, v of state_actions when v and v._
    _state[k] = statue v, delay_nested, do (k)=>(sub_state)=> # closure for k
      _state[k] = sub_state # executes as _nested


  # saving new state in closure
  save_state = (state)=>
    do schedule
    _state = state


  schedule = =>
    unless _scheduled
      _scheduled = true
      # lazy parent update
      delayed update_parent
    return


  update_parent = =>
    _scheduled = false
    proto_state = _state
    _state = create null
    # merging prototype chain state
    _state[k] = proto_state[k] for k of proto_state
    do _nested

    level_up _state
    return

This function is a little overloaded, it's a getter/setter but also is a function wrapper. You can access it like this yourState._(updated). The wrapper will return a twin of your function that calls yours and passes a copy of latest state as the second argument. State will update, if the copy is mutated or a new object returned. If your function returns a new function, it will be wrapped in the same manner. So we support state updates for deeply curried functions.

  # curry down or make state
  _state._ = update_state = (arg)=>
    if is_function arg
      inject_state arg
    else
      if arg
        save_state assign create(_state), arg
      else
        _state

inject_state is a higher order function that does the magic. It produces a cheap clone if current state by setting current state as its prototype. Please note that such a clone has no own properties, and all property accees falls back to its prototype. If we mutate such a clone, new properties are easily detected

  inject_state = (f)=>(x)=>
    # _state as prototype of cloned
    cloned = create _state
    y = f x, cloned

    for own k of cloned
      # mutation detected
      mutated = true
      save_state cloned
      break

    if is_function y
      # recursevely currying down
      inject_state y
    else
      if y and not mutated and y isnt cloned and not y.then # not promise
        save_state assign cloned, y
      y

Now let's wrap all of your actions and set under the _ property. That's it! You new state machine is ready!

  # bind actions to state
  for k, action of actions
    update_state[k] = inject_state action


  _state