@epegzz/memoize

1.0.1 • Public • Published

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

Package Sidebar

Install

npm i @epegzz/memoize

Weekly Downloads

2

Version

1.0.1

License

MIT

Unpacked Size

115 kB

Total Files

7

Last publish

Collaborators

  • epegzz