|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const util = require('util'); |
| 5 | + |
| 6 | +// Production implementation from Metasync library |
| 7 | +// See: https://github.com/metarhia/metasync |
| 8 | + |
| 9 | +const metasync = {}; |
| 10 | + |
| 11 | +function Memoized() { |
| 12 | +} |
| 13 | + |
| 14 | +util.inherits(Memoized, Function); |
| 15 | + |
| 16 | +metasync.memoize = (fn) => { |
| 17 | + const cache = new Map(); |
| 18 | + |
| 19 | + const memoized = function(...args) { |
| 20 | + const callback = args.pop(); |
| 21 | + const key = args[0]; |
| 22 | + const record = cache.get(key); |
| 23 | + if (record) { |
| 24 | + callback(record.err, record.data); |
| 25 | + return; |
| 26 | + } |
| 27 | + fn(...args, (err, data) => { |
| 28 | + cache.set(key, { err, data }); |
| 29 | + callback(err, data); |
| 30 | + }); |
| 31 | + }; |
| 32 | + |
| 33 | + const fields = { |
| 34 | + cache, |
| 35 | + timeout: 0, |
| 36 | + limit: 0, |
| 37 | + size: 0, |
| 38 | + maxSize: 0 |
| 39 | + }; |
| 40 | + |
| 41 | + Object.setPrototypeOf(memoized, Memoized.prototype); |
| 42 | + return Object.assign(memoized, fields); |
| 43 | +}; |
| 44 | + |
| 45 | +Memoized.prototype.clear = function() { |
| 46 | + this.cache.clear(); |
| 47 | +}; |
| 48 | + |
| 49 | +// Usage |
| 50 | + |
| 51 | +fs.readFile = metasync.memoize(fs.readFile); |
| 52 | + |
| 53 | +fs.readFile('6-metasync.js', (err, data) => { |
| 54 | + console.log('data length: ' + data.length); |
| 55 | + fs.readFile('6-metasync.js', (err, data) => { |
| 56 | + console.log('data length: ' + data.length); |
| 57 | + }); |
| 58 | +}); |
0 commit comments