Last active
February 6, 2016 19:40
-
-
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*
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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