Skip to content

Instantly share code, notes, and snippets.

@AutoSponge
Last active October 13, 2015 22:57
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 AutoSponge/4268544 to your computer and use it in GitHub Desktop.
Save AutoSponge/4268544 to your computer and use it in GitHub Desktop.
another idea for flow control
function Plinko() {
this.tree = {};
}
Plinko.prototype.add = function (from, fn) {
var leaf,
callback;
if (typeof from === "string") {
leaf = from;
callback = fn;
} else {
leaf = "root";
callback = from;
}
var branch = this.tree[leaf] = this.tree[leaf] || [];
branch.push(callback);
};
Plinko.prototype.run = function (args, that, from, options) {
var branch = this.tree[from || "root"];
var results = [];
var data = options || {};
var result,
resultType;
for (var i = 0, len = branch && branch.length || 0; i < len; i += 1) {
result = branch[i].call(that, args, data);
resultType = typeof result;
if (resultType !== "undefined") {
if (resultType === "object") {
data[result.go] = result.data || {};
results.push(result.go);
} else {
results.push(result);
}
}
}
for (i = 0, len = results.length; i < len; i += 1) {
this.run(args, that, results[i], data);
}
};
var p = new Plinko();
p.add(function (args, data) {
console.log("init", args, data);
return "step1";
});
p.add("step1", function (args, data) {
console.log("step1", args, data);
return data.step1 === "stop" || "step2";
});
p.add("step2", function (args, data) {
console.log("step2", args, data);
return {
go: "step1",
data: "stop"
};
});
p.run([
1, 2, 3
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment