Skip to content

Instantly share code, notes, and snippets.

@jczimm
Last active February 6, 2016 19:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jczimm/f6a61811eabcb7bbe796 to your computer and use it in GitHub Desktop.
Save jczimm/f6a61811eabcb7bbe796 to your computer and use it in GitHub Desktop.
Tiny right-to-left control flow utility (experiment) utilizing context binding. Allows both sync and async steps. Syntax for context-binding simplified by the experimental strawman operator (https://github.com/zenparsing/es-function-bind). No error/misuse handling. *Uses ES7 features*
// Syntax 1:
s.val(13)::third::second::first::s.run();
// Syntax 2: (-> s.val completely unnecessary)
third::second::first::s.run(13);
//
// Example programmatic creation of a chain
let chain = third;
chain = chain::second;
chain = chain::first;
chain::s.run(13);
//
function first() {
this::s.async(function run(i) {
console.log("first", this, i);
return new Promise((resolve, reject) => {
setTimeout(() => resolve(this + 2), 100);
});
});
}
function second() {
this::s.chain(function run(i) {
console.log("second", this, i);
return this + 3;
});
}
function third() {
this::s.chain(function run(i) {
console.log("third", this, i);
return this;
});
}
const s = (() => {
let object, i = 0;
return {
// initialize the value that is passed as `obj` to each callback passed to `chain`
val(obj) {
object = obj;
i = 0;
},
// run code (in `cb` function) safely in the flow
chain(cb) {
object = object::cb(i++);
if (typeof this === "function") this();
},
// async chain
async async(cb) {
object = await object::cb(i++);
if (typeof this === "function") this();
},
// initiate flow; can be passed initial value
run(obj) {
if (obj) {
object = obj;
i = 0;
}
this();
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment