Created
February 11, 2021 23:50
-
-
Save northamerican/8e491df8bd5ec9acf091512c4d757eb4 to your computer and use it in GitHub Desktop.
Simple caching in Javascript using the new Logical nullish assignment (??=) operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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