-
Notifications
You must be signed in to change notification settings - Fork 1
/
topologica.js
81 lines (67 loc) · 1.79 KB
/
topologica.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
const keys = Object.keys;
export default reactiveFunctions => {
const state = {};
const functions = {};
const edges = {};
const invoke = property => {
functions[property]();
};
const allDefined = dependencies => {
const arg = {};
return dependencies.every(property => {
if (state[property] !== undefined){
arg[property] = state[property];
return true;
}
}) ? arg : null;
};
keys(reactiveFunctions).forEach(property => {
const reactiveFunction = reactiveFunctions[property];
let dependencies = reactiveFunction.dependencies;
const fn = dependencies ? reactiveFunction : reactiveFunction[0];
dependencies = dependencies || reactiveFunction[1];
dependencies = dependencies.split
? dependencies.split(',').map(str => str.trim())
: dependencies;
dependencies.forEach(input => {
(edges[input] = edges[input] || []).push(property);
});
functions[property] = () => {
const arg = allDefined(dependencies);
if (arg) {
state[property] = fn(arg);
}
};
});
const depthFirstSearch = sourceNodes => {
const visited = {};
const nodeList = [];
const search = node => {
if (!visited[node]) {
visit(node);
nodeList.push(node);
}
};
const visit = node => {
visited[node] = true;
edges[node] && edges[node].forEach(search);
}
sourceNodes.forEach(visit);
return nodeList;
}
const set = function(stateChange) {
depthFirstSearch(keys(stateChange).map(property => {
if (state[property] !== stateChange[property]) {
state[property] = stateChange[property];
return property;
}
}))
.reverse()
.forEach(invoke);
return this;
};
return {
set,
get: () => state
};
};