Skip to content

Instantly share code, notes, and snippets.

@olchyk98
Created September 14, 2024 17:31
Show Gist options
  • Select an option

  • Save olchyk98/261686beca11aa54c2a620a41f2f32d8 to your computer and use it in GitHub Desktop.

Select an option

Save olchyk98/261686beca11aa54c2a620a41f2f32d8 to your computer and use it in GitHub Desktop.
// env::common.js
const toString = require('./src/toString') // R.string
const maxScore = 100
function memorizeForMe (fn) {
const cache = new Map()
const cacheScore = new Map()
return (...args) => {
// NOTE: toString() since it can handle complex structures.
const id = toString(args)
// Decrease score for all ids, except current
cacheScore.forEach((v, k, i) => {
if(k === id) return
// Purge old cache
if(v <= 1) {
i.delete(k)
cache.delete(k)
return
}
// Decrease value of other entries
return i.set(k, v - 1)
})
if(cache.has(id)) {
return cache.get(id)
}
const result = fn(...args)
// Cache the result
cache.set(id, result)
// And assign maxScore to the new entry, it
// will decrease over time
cacheScore.set(id, maxScore)
return result
}
}
const rand = memorizeForMe(() => Math.random())
const k = [rand(1), rand(), rand(2), rand(1)]
console.log(k)
//[
//0.10202677372401414,
//0.07587689343613024,
//0.7744437228888266,
//0.10202677372401414
//]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment