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

memo-bind

v2.0.3

Published

"Memoized binding of function arguments"

Downloads

18

Readme

memo-bind

Memoized binding of arguments to functions. Very useful for React and Preact!

You can use memo-bind to prevent allocating a new function on each render when all you want to do is bind a value as an argument to a function. The standard way to avoid this is to break out a child component and bind the value to that instead, but sometimes that is a bit cumbersome. By using memo-bind you can avoid having to refactor too much, while also avoiding unnecessary function allocations and unnecessary renders.

Installation

npm i memo-bind

Example Usage

memo-bind exports two functions, partial and bind. The only difference between the two is that bind takes a thisArg

import { partial, bind } from 'memo-bind'
//...
let cache = new Map()
//...
let memoizedFn = bind(cache, thisArg, fn, ...argumentsToBind)
let memoizedFn2 = partial(cache, fn, ...argumentsToBind)

memo-bind does not initiate its own cache. This makes it easier for the user to control the lifecycle of the cache, destroying it, clearing it, or replacing it whenever and however they want. You must provide an ES6 Map as the cache for memo-bind.

Example usage with React / Preact

Note that the counter feature also demonstrates that these bindings functions avoid reallocting functions on each render. You should only see one log in the console.

import { h, Component } from 'preact'
import style from './style'

import { partial, bind } from 'memo-bind'

export default class Example extends Component {
  state = {
    items: {
      1: {name: "item 1", id: '1'},
      2: {name: "item 2", id: '2'}
    },
    count: 0
  }

  componentDidMount() {
    this.interval = setInterval(
      () => this.setState(state => ({count: state.count + 1})), 
      1000
    )
  }

  multiply = factor => this.setState(
    state => ({count: state.count * factor}))

  // This is a function that needs the thisArg and an additional argument bound to it
  deleteItem(id) {
    // A little helper for making mutation free updates
    function omit(key, obj) {
      return Object.assign({}, 
                           ...Object.keys(obj)
                                    .filter(k => k !== key)
                                    .map(k => ({[k]: obj[k]})))
    }
    this.setState({items: omit(id, this.state.items)})
  }

  // This is a function that only needs an argument bound, but not the thisArg
  capitalizeName = item => {
    let {items} = this.state
    this.setState(state => Object.assign(items, {
      [item.id]: Object.assign(item, {name: item.name.toUpperCase()})
    }))
  }

  // If you declare the cache as a property of the component then
  // its lifecycle will match that of the component and you 
  // shouldn't have to worry too much about cleanup or unbounded
  // cache sizes
  fnCache = new Map()

  render({}, { items, count }) {
    //Normally you would just stick this straight into the jsx but we need 
    //to save the result for demonstration purposes
    let double = partial(this.fnCache, this.multiply, 2)
    if (this.double !== double) {
      this.double = double
      console.log('created new double function')
    }

    return (
      <div class={style.container}>
        <button onClick={double}>Double</button>
        <div class={style.counter}>{count}</div>
        {Object.keys(items).map(itemId => {
          let item = items[itemId]
          return (
          <div class={style.item}>
            {item.name}
            <button onClick={partial(this.fnCache, this.capitalizeName, item)}>
              Capitalize
            </button>
            <button onClick={bind(this.fnCache, this.deleteItem, this, item.id)}>
              Delete
            </button>
          </div>
        )})}
      </div>
    )
  }
}