Created
September 14, 2024 17:31
-
-
Save olchyk98/261686beca11aa54c2a620a41f2f32d8 to your computer and use it in GitHub Desktop.
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
| // 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