-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
101 lines (86 loc) · 2.69 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
94
95
96
97
98
99
100
101
/**
* filter-observable-store - https://github.com/flams/filter-observable-store
* Copyright(c) 2015 Olivier Scherrer <[email protected]>
* MIT Licensed
*/
"use strict";
module.exports = function Filter(observableStore) {
if (!isObservableStore(observableStore)) {
throw new TypeError("Filter needs to be initialized with a valid observable store");
}
var _storeObservable = observableStore.getStoreObservable();
var _predicate = getDefaultPredicate();
return extend(observableStore, {
setFilter: function (filterFn, scope) {
setFilter(getPredicate(filterFn, scope));
},
clearFilter: function () {
setFilter(getDefaultPredicate());
},
loop: function (fn, scope) {
observableStore.loop(function (value) {
if (_predicate(value)) {
fn.apply(scope, arguments);
}
});
},
count: function () {
return observableStore
.proxy("filter", _predicate)
.length;
},
has: function (item) {
var hasItem = observableStore.has(item);
if (hasItem) {
return _predicate(observableStore.get(item));
} else {
return false;
}
},
watchValue: function (index, callback, scope) {
return observableStore.watchValue(index, function (newValue) {
if (_predicate(newValue)) {
callback.apply(scope, arguments);
}
});
},
watch: function (action, callback, scope) {
return observableStore.watch(action, function (index, newValue, oldValue) {
if ((action == "deleted" && _predicate(oldValue))
|| (action != "deleted" && _predicate(newValue))) {
callback.apply(scope, arguments);
}
});
}
});
function setFilter(predicate) {
_predicate = predicate;
_storeObservable.notify("filtered");
}
};
function isObservableStore(store) {
return [
"count",
"loop",
"watch",
"watchValue"].every(function (fn) {
return typeof store[fn] == "function";
});
}
function extend(obj, fns) {
return Object.create(obj, Object.keys(fns)
.reduce(function (memo, name) {
memo[name] = {
value: fns[name]
};
return memo;
}, {}));
}
function getDefaultPredicate() {
return function () { return true };
}
function getPredicate(fn, scope) {
return function (value) {
return fn.call(scope, value);
};
}