forked from exceptionless/Exceptionless.JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInMemoryStorage.ts
More file actions
60 lines (49 loc) · 1.47 KB
/
InMemoryStorage.ts
File metadata and controls
60 lines (49 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { IEvent } from '../models/IEvent';
import { IStorage } from './IStorage';
import { IStorageItem } from './IStorageItem';
export class InMemoryStorage<T> implements IStorage<T> {
private _items:IStorageItem<T>[] = [];
private _maxItems:number;
constructor(maxItems?:number) {
this._maxItems = maxItems > 0 ? maxItems : 250;
}
public save(path:string, value:T):boolean {
if (!path || !value) {
return false;
}
this.remove(path);
if (this._items.push({ created: new Date().getTime(), path: path, value: value }) > this._maxItems) {
this._items.shift();
}
return true;
}
public get(path:string):T {
var item:IStorageItem<T> = path ? this.getList(`^${path}$`, 1)[0] : null;
return item ? item.value : null;
}
public getList(searchPattern?:string, limit?:number):IStorageItem<T>[] {
var items = this._items; // Optimization for minifier
if (!searchPattern) {
return items.slice(0, limit);
}
var regex = new RegExp(searchPattern);
var results:IStorageItem<T>[] = [];
for (var index = 0; index < items.length; index++) {
if (regex.test(items[index].path)) {
results.push(items[index]);
if (results.length >= limit) {
break;
}
}
}
return results;
}
public remove(path:string):void {
if (path) {
var item = this.getList(`^${path}$`, 1)[0];
if (item) {
this._items.splice(this._items.indexOf(item), 1);
}
}
}
}