This repository has been archived by the owner on Oct 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
93 lines (89 loc) · 2.38 KB
/
index.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const { LocalStorage } = require("node-localstorage");
const { EventEmitter } = require("events");
function ArrayToDisk(location, size) {
const loc = location ? location.toString() : null;
const sizeint = parseInt(size, 10);
const sz = Number.isInteger(sizeint) ? sizeint : 50000;
let k = 0;
Array.call(this);
if (loc) {
this.storage = new LocalStorage(loc, sz);
const data = JSON.parse(this.storage.getItem("data") || "[]");
for (k; k < data.length; k += 1) {
this[this.length + k] = data[k];
}
this.length = this.length + data.length;
}
}
ArrayToDisk.prototype = Object.create(Array.prototype, {
setEventEmitter: {
value(emitter, errorEvent = "error") {
this.emitter = emitter;
this.errorEvent = errorEvent;
},
writable: true,
enumerable: true,
configurable: true
},
shift: {
value() {
if (this.storage) {
const data = JSON.parse(this.storage.getItem("data") || "[]");
data.shift();
try {
this.storage.setItem("data", JSON.stringify(data));
} catch (e) {
if (this.emitter instanceof EventEmitter) {
this.emitter.emit(this.errorEvent, e);
}
}
}
return this.length ? this.splice(0, 1)[0] : undefined;
},
writable: true,
enumerable: true,
configurable: true
},
push: {
value(...args) {
if (this.storage) {
const data = JSON.parse(this.storage.getItem("data") || "[]");
let k = 0;
for (k; k < args.length; k += 1) {
data.push(args[k]);
}
try {
this.storage.setItem("data", JSON.stringify(data));
} catch (e) {
if (this.emitter instanceof EventEmitter) {
this.emitter.emit(this.errorEvent, e);
}
}
}
let i = 0;
for (i; i < args.length; i += 1) {
let len = this.length;
this[len] = args[i];
len += 1;
this.length = len;
}
return this.length;
},
writable: true,
enumerable: true,
configurable: true
},
deleteLocation: {
value() {
if (this.storage) {
this.storage._deleteLocation(); // eslint-disable-line no-underscore-dangle
delete this.storage;
}
},
writable: true,
enumerable: true,
configurable: true
}
});
ArrayToDisk.prototype.constructor = ArrayToDisk;
module.exports = ArrayToDisk;