1.0.1 • Published 6 years ago

@epegzz/memoize v1.0.1

Weekly downloads
20
License
MIT
Repository
github
Last release
6 years ago

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