@epegzz/memoize

ES6 class method decorator for caching method calls

Stats

StarsIssuesVersionUpdatedCreatedSize
@epegzz/memoize
001.0.13 years ago3 years agoMinified + gzip package size for @epegzz/memoize in KB

Readme

memoize

ES6 class method decorator for caching method calls

Travis Maintainability Codecov npm version npm installs dependencies

memoize as a little ES6 class method decorator that allows you to cache method calls. If you call the method twice with the same function arguments, the second call will return the cached results:

import memoize from '@epegzz/memoize'

class MemoizeDemo {

  @memoize
  doExpensiveCall() {
   console.log('Called with', JSON.stringify(arguments))
  }
  
  constructor () {
    this.doExpensiveCall('A') // prints `Called with ["A"]`
    this.doExpensiveCall('B') // prints `Called with ["B"]`
    this.doExpensiveCall('A') // no log output
    this.doExpensiveCall('A', 'C') // prints `Called with ["A", "C"]`
  }
}

Equality is checked for each argument using the === operator.

  '1' === '1' // true
  'A' === 'A' // true
  'A' === 'B' // false
  ['A'] === ['A'] // false
  { 1: 2 } === { 1: 2 } // false

Also works with async methods:

import memoize from '@epegzz/memoize'

class MemoizeDemo {

  @memoize
  async fetchWeather(cityName) {
    return fetch(`http://myweather.com/cities/${cityName}`)
  }

  constructor () {
    this.fetchWeather('Berlin').then(…)
    this.fetchWeather('Berlin').then(…) // no fetch was done here
  }
}

Install

using npm

npm install @epegzz/memoize --save

using yarn

yarn add @epegzz/memoize

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.