Skip to content

Instantly share code, notes, and snippets.

@damusix
Last active May 2, 2019 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damusix/94c748ee5f017c7557b0aceedb094e8a to your computer and use it in GitHub Desktop.
Save damusix/94c748ee5f017c7557b0aceedb094e8a to your computer and use it in GitHub Desktop.
Very inefficient and redundant implementation of meiosis pattern using browser's `ReadableStream` http://meiosis.js.org
const noop = () => {};
const store = {
// Initial state
state: {
working: true,
items: [],
},
actions: (update) => ({
getThings: () => {
update({
...store.state,
items: [1,2,3]
});
},
breakThings: () => {
update({
...store.state,
working: false
});
},
fixThings: () => {
update({
...store.state,
working: true
});
}
})
};
// Need a place to store listeners bc of nature of ReadableStream
const listeners = [];
// Attaches functions to listeners
const states = (fn) => listeners.push(fn);
// Predfine because we're limited by implementation
let pushStream, stream, reader;
// Create a DOM stream
stream = new ReadableStream({
start(controller) {
// Pushes state to stream then reads and executes listeners
pushStream = (state) => {
reader = reader || stream.getReader();
controller.enqueue(state);
reader
.read()
.then(({ value }) => {
listeners.forEach(fn => fn(value))
});
};
}
});
// Merges state and pushes to stream
update = (state) => {
store.state = {
...store.state,
...state
};
pushStream(store.state);
};
// Bind update function
const actions = store.actions(update);
// Add log listener
states(console.log);
const el = document.createElement('div');
document.body.appendChild(el);
// Write to document listener
states((state) => {
const pre = document.createElement('pre');
pre.innerHTML = JSON.stringify(state, null, 4);
el.appendChild(pre);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment