Last active
October 13, 2015 22:57
-
-
Save AutoSponge/4268544 to your computer and use it in GitHub Desktop.
another idea for flow control
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
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