UNPKG

2.91 kBJavaScriptView Raw
1import IterResult from './iterresult';
2import dateutil from './dateutil';
3import { isArray } from './helpers';
4var Cache = /** @class */ (function () {
5 function Cache() {
6 this.all = false;
7 this.before = [];
8 this.after = [];
9 this.between = [];
10 }
11 /**
12 * @param {String} what - all/before/after/between
13 * @param {Array,Date} value - an array of dates, one date, or null
14 * @param {Object?} args - _iter arguments
15 */
16 Cache.prototype._cacheAdd = function (what, value, args) {
17 if (value) {
18 value =
19 value instanceof Date
20 ? dateutil.clone(value)
21 : dateutil.cloneDates(value);
22 }
23 if (what === 'all') {
24 this.all = value;
25 }
26 else {
27 args._value = value;
28 this[what].push(args);
29 }
30 };
31 /**
32 * @return false - not in the cache
33 * null - cached, but zero occurrences (before/after)
34 * Date - cached (before/after)
35 * [] - cached, but zero occurrences (all/between)
36 * [Date1, DateN] - cached (all/between)
37 */
38 Cache.prototype._cacheGet = function (what, args) {
39 var cached = false;
40 var argsKeys = args ? Object.keys(args) : [];
41 var findCacheDiff = function (item) {
42 for (var i = 0; i < argsKeys.length; i++) {
43 var key = argsKeys[i];
44 if (String(args[key]) !== String(item[key])) {
45 return true;
46 }
47 }
48 return false;
49 };
50 var cachedObject = this[what];
51 if (what === 'all') {
52 cached = this.all;
53 }
54 else if (isArray(cachedObject)) {
55 // Let's see whether we've already called the
56 // 'what' method with the same 'args'
57 for (var i = 0; i < cachedObject.length; i++) {
58 var item = cachedObject[i];
59 if (argsKeys.length && findCacheDiff(item))
60 continue;
61 cached = item._value;
62 break;
63 }
64 }
65 if (!cached && this.all) {
66 // Not in the cache, but we already know all the occurrences,
67 // so we can find the correct dates from the cached ones.
68 var iterResult = new IterResult(what, args);
69 for (var i = 0; i < this.all.length; i++) {
70 if (!iterResult.accept(this.all[i]))
71 break;
72 }
73 cached = iterResult.getValue();
74 this._cacheAdd(what, cached, args);
75 }
76 return isArray(cached)
77 ? dateutil.cloneDates(cached)
78 : cached instanceof Date
79 ? dateutil.clone(cached)
80 : cached;
81 };
82 return Cache;
83}());
84export { Cache };
85//# sourceMappingURL=cache.js.map
\No newline at end of file