Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save northamerican/8e491df8bd5ec9acf091512c4d757eb4 to your computer and use it in GitHub Desktop.
Save northamerican/8e491df8bd5ec9acf091512c4d757eb4 to your computer and use it in GitHub Desktop.
Simple caching in Javascript using the new Logical nullish assignment (??=) operator
// Simple caching in Javascript using the new Logical nullish assignment (??=) operator
class FibClass {
// Private field to store a value
#fib = null
// Fibonacci sequence method (recursive calculation)
f (n) {
return n < 3 ? 1 : this.f(n - 1) + this.f(n - 2)
}
// Getter that caches and retrieves a value
get fib () {
// If null, assign to #fib a calculated value and return it
// Otherwise return the cached value
return this.#fib ??= this.f(40)
}
}
// Make an instance of FibClass
const fibClass = new FibClass()
// Get the value (this performs an expensive calculation)
fibClass.fib
// Get it again (this returns the now cached value instantly)
fibClass.fib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment