Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.
⭐ ⭐
A:
Closures, which create private variables and extend their lifetime, can be used as caching modules to keep private variables in memory as caches until the page is destroyed.
Below, I use two examples of how to implement a caching module using closures.
Example 1 Calculation of cache time
Suppose you have a calculation that is very time-consuming, you need to design a cache module to store the calculation results. Before the next calculation, you need to check whether there is a value in the cache. If there is a value, you will directly return it, so that you do not need to recalculate every time.
We simulate a very time-consuming calculation by counting prime numbers. The code for calculating prime numbers is as follows:
function isPrime (n) {
let res = n > 1
for (let i = 2; i < n; i++) {
if (n % i === 0) {
res = false
break}}return res
}
console.log(isPrime(2)) // true
console.log(isPrime(3)) // true
console.log(isPrime(4)) // false
console.log(isPrime(5)) // true
Copy the code
Next, a cache object is used to cache the results. If there is no value in the cache, it is stored there, and if there is a value in the cache, it is returned.
const cache = {}
function isPrime (n) {
if (n in cache) {
console.log(` in the cache${n}, directly return :>> ', cache[n])
return cache[n]
}
let res = n > 1
for (let i = 2; i < n; i++) {
if (n % i === 0) {
res = false
break}}console.log(There is no ` cache${n}, save it in :>> ', res)
cache[n] = res
return res
}
Copy the code
Test it out:
isPrime(3)
isPrime(4)
isPrime(5)
isPrime(5)
isPrime(5)
console.log('cache :>> ', cache)
Copy the code
The above code can implement caching, but the biggest problem is that the cache needs to define a global variable cache.
At this point, the closure appears, and the cache variable can be hidden with the closure.
Define cache as an anonymous function, and return the function that calculates prime numbers inside the anonymous function, so that the function that calculates prime numbers can be called externally, and the cache object is hidden in a closure, so that the cache object is not accessible globally.
const isPrime = (function () {
const cache = {}
return function (n) {
if (n in cache) {
console.log(` in the cache${n}, directly return :>> ', cache[n])
return cache[n]
}
let res = n > 1
for (let i = 2; i < n; i++) {
if (n % i === 0) {
res = false
break}}console.log(There is no ` cache${n}, save it in :>> ', res)
cache[n] = res
return res
}
})()
isPrime(3)
isPrime(4)
isPrime(5)
isPrime(5)
isPrime(5)
Copy the code
Case 2 imitation localStorage
Achieve a simple function similar to localStorage, can be set method value, get method value.
The principle is the same as in example 1, which defines the cache inside an anonymous function.
This anonymous function returns an object on which the cache module’s get and set methods store data to a cache object inside the anonymous function, and get reads the data.
const myStorage = (function () {
const cache = {}
return {
set: (key, val) = > {
cache[key] = val
},
get: (key) = > {
if (key in cache) {
return cache[key]
}
}
}
})()
myStorage.set('name'.'lin')
myStorage.set('age'.18)
console.log(myStorage.get('name'))
console.log(myStorage.get('age'))
Copy the code
At the end
If my article is helpful to you, your 👍 is my biggest support ^_^
You can also follow the front End Daily Question column in case you lose contact
I’m Allyn, export insight technology, goodbye!
The last:
The relationship between the “front-end Daily Ask (30)” closure and the immediate execution function IIFE
Next up:
How do CLOSURES implement a singleton pattern?