Files: d2f2697f296dd39aed6a8b63c6d04a736a7db5b3 / node_modules / asyncmemo / index.js
1839 bytesRaw
1 | var has = Object.prototype.hasOwnProperty |
2 | |
3 | function toArgString() { |
4 | return [].join.call(arguments) |
5 | } |
6 | |
7 | module.exports = function (opts, fn /*, preArgs... */) { |
8 | var preArgs = [].slice.call(arguments, 2) |
9 | if (typeof opts === 'function') { |
10 | if (arguments.length >= 2) preArgs.unshift(fn) |
11 | fn = opts |
12 | opts = {} |
13 | } |
14 | var cache = |
15 | opts.cache === false ? null : |
16 | opts.cache === true || opts.cache == null ? new Storage() : |
17 | opts.cache |
18 | var callbacks = {/* arg: [callback] */} |
19 | var toString = opts.asString || toArgString |
20 | |
21 | var memoized = function (/* args..., cb */) { |
22 | var args = [].slice.call(arguments) |
23 | var cb = args.pop() |
24 | var memo = toString.apply(this, args) |
25 | if (cache && cache.has(memo)) { |
26 | var self = this |
27 | return process.nextTick(function () { |
28 | if (cache.has(memo)) |
29 | cb.call(self, null, cache.get(memo)) |
30 | else |
31 | run.call(self, args, memo, cb) |
32 | }) |
33 | } |
34 | run.call(this, args, memo, cb) |
35 | } |
36 | memoized.cache = cache |
37 | return memoized |
38 | |
39 | function run(args, memo, cb) { |
40 | if (has.call(callbacks, memo)) |
41 | return callbacks[memo].push([this, cb]) |
42 | var cbs = callbacks[memo] = [[this, cb]] |
43 | fn.apply(this, preArgs.concat(args, function (err, result) { |
44 | if (!err && cache) |
45 | cache.set(memo, result) |
46 | while (cbs.length) { |
47 | cb = cbs.shift() |
48 | cb[1].call(cb[0], err, result) |
49 | } |
50 | delete callbacks[memo] |
51 | })) |
52 | } |
53 | } |
54 | |
55 | function Storage() { |
56 | this.data = {} |
57 | } |
58 | Storage.prototype.has = function (key) { |
59 | return has.call(this.data, key) |
60 | } |
61 | Storage.prototype.get = function (key) { |
62 | return this.data[key] |
63 | } |
64 | Storage.prototype.set = function (key, value) { |
65 | this.data[key] = value |
66 | } |
67 | Storage.prototype.remove = function (key) { |
68 | delete this.data[key] |
69 | } |
70 | Storage.prototype.clear = function (key) { |
71 | this.data = {} |
72 | } |
73 |
Built with git-ssb-web