This repository has been archived by the owner on Sep 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 65
/
localStorage.js
82 lines (67 loc) · 1.96 KB
/
localStorage.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
var _ = require("underscore")._;
var LocalStorageBackend = function(options) {
options = options || {};
var name = options.name || Math.floor(Math.random() * 100000);
this.prefix = 'classifier.bayesian.' + name;
if (options.testing) {
this.storage = {};
}
else {
this.storage = localStorage;
}
this.storage[this.prefix + '.cats'] = '{}';
}
LocalStorageBackend.prototype = {
async : false,
getCats : function() {
return JSON.parse(this.storage[this.prefix + '.cats']);
},
setCats : function(cats) {
this.storage[this.prefix + '.cats'] = JSON.stringify(cats);
},
getWordCount : function(word) {
return JSON.parse(this.storage[this.prefix + '.words.' + word] || '{}');
},
setWordCount : function(word, counts) {
this.storage[this.prefix + '.words.' + word] = JSON.stringify(counts);
},
getWordCounts : function(words) {
var counts = {};
words.forEach(function(word) {
counts[word] = this.getWordCount(word);
}, this);
return counts;
},
incCounts : function(catIncs, wordIncs) {
var cats = this.getCats();
_(catIncs).each(function(inc, cat) {
cats[cat] = cats[cat] + inc || inc;
}, this);
this.setCats(cats);
_(wordIncs).each(function(incs, word) {
var wordCounts = this.getWordCount(word);
_(incs).each(function(inc, cat) {
wordCounts[cat] = wordCounts[cat] + inc || inc;
}, this);
this.setWordCount(word, wordCounts);
}, this);
},
toJSON : function() {
var words = {};
var regex = new RegExp("^" + this.prefix + "\\.words\\.(.+)$")
for (var item in this.storage) {
var match = regex.exec(item);
if (match) {
words[match[1]] = JSON.parse(this.storage[item]);
}
}
return {
cats: JSON.parse(this.storage[this.prefix + '.cats']),
words: words
};
},
fromJSON : function(json) {
this.incCounts(json.cats, json.words);
}
}
exports.LocalStorageBackend = LocalStorageBackend;