-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.js
51 lines (47 loc) · 1.25 KB
/
core.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
/**
* THE LIBRARY WORKS SAME REACT + REDUX
*/
// A tagged template literals to get html string
export default function html([first, ...strings], ...args) {
return (
args
.reduce((acc, curr) => acc.concat(curr, strings.shift()), [first])
// Remove all Falsy values except 0
.filter((x) => (x && x !== true) || x === 0)
.join('')
);
}
export function createStore(reducer) {
let state = reducer();
/**
* I use Map here for 2 main reasons:
* - can loop through all keys
* - key can be a object which key in object({}) can't be
*/
const roots = new Map();
function render() {
for (const [root, component] of roots) {
const _component = component();
root.innerHTML = _component;
}
}
return {
attach(component, root) {
roots.set(root, component);
render();
},
/**
* selector: function select data in state
* Finally assign all props, state and arguments into component's props
*/
connect(selector = (state) => state) {
return (component) =>
(props, ...args) =>
component(Object.assign({}, props, selector(state), ...args));
},
dispatch(action, ...args) {
state = reducer(state, action, args);
render();
},
};
}