npm.io
1.0.2 • Published 6 years ago

fire-when

Licence
MIT
Version
1.0.2
Deps
0
Size
919 kB
Vulns
0
Weekly
0

fire-when

The MIT License code style: prettier manpm npm Commitizen friendly

Call a function when a certain criterion is met.

Documentation.

Why

To reduce the function calls. for example, in a react application, if some state mutations are expensive and repeat at very high frequency, you could use this package to reduce the state mutations, if dropping some state mutation doesn't matter.

Installation

npm i fire-when

Quick start


const wrappedF = arg => arg
// realF will will called when f is called 3N times.
const wrappingF = fireWhen(counter => counter % 3 === 0)(wrappedF)

wrappingF('foo') // output foo
wrappingF('foo') // output undefined
wrappingF('foo') // output undefined
wrappingF('foo') // output foo

A more complex but somewhat ridiculous example

import React from 'react';
import fireWhen from 'fire-when';

class App extends React.Component {
  state = {
    ts: Date.now(),
  }

  componentDidMount() {
    // update ts every 10ms? 10 * 100ms actually
    setInterval(this.updateTs, 10);
  }

  updateTs = fireWhen(i => i % 100 === 0)(() => {
    this.setState(({ts}) => ({
      ts: Date.now()
    }));
  })

  render() {
    return (<div>{this.state.ts}</div>);
  }
}

Contribution

yarn test-watch