@justinseibert/depends-on
TypeScript icon, indicating that this package has built-in type declarations

1.2.1 • Public • Published

dependsOn

NPM version NPM downloads Build status

A decorator for caching class getters and updating the cache based on dependent properties

Installation

npm install @justinseibert/depends-on --save

Support

Make sure ES6 @decorators are supported in your environment. For instance, in .tsconfig:

{
  "compilerOptions": {
    ...
    "experimentalDecorators": true,
  }
}

Usage

Dependency Array

Apply decorator to a public get accessor. Add string identifiers of other properties to the dependency array that will trigger a cache update.

Properties added to the dependency array are also tracked in the cache, but do not require their own decoration.

If all of the dependencies are unchanged, the accessor will return the last cached value instead of executing it's underlying function.

import dependsOn from '@justinseibert/depends-on'

class Plant {
  hasWater = true
  hasLight = true

  @dependsOn(['hasWater', 'hasLight'])
  public get canGrow() {
    return this.hasWater && this.hasLight
  }
}

Permanent Caching

If the dependency array is empty, the value of the function will be permanently cached during it's first access.

class Boulder {
  @dependsOn([])
  public get mineralComposition() {
    const feldspar = Math.random()
    const quartz: 1 - feldspar

    return {s
      feldspar,
      quartz,
    }
  }
}

Setter Functions

A setter function will update the cached value and perform any additional computation within.

Related dependencies that are updated within the set function are cache-validated so that they do not needlessly trigger a reload during the next get

class Lake {
  volume = 100
  topography = [ ... ]

  @dependsOn(['topography', 'volume'])
  public get shoreline() {
    const perimeter = []
    this.topography.forEach((sector) => {
      perimeter.push(...calculatePoints(sector, this.volume))
    })
    return perimeter
  }

  public set shoreline(perimeter) {
    this.volume = calculateVolume(perimeter, this.topography)
  }
}

License

MIT

Package Sidebar

Install

npm i @justinseibert/depends-on

Weekly Downloads

3

Version

1.2.1

License

MIT

Unpacked Size

63 kB

Total Files

12

Last publish

Collaborators

  • justinseibert