Created
July 19, 2018 18:48
-
-
Save SethVandebrooke/db80516fcc99ebf6014c8edc4edef221 to your computer and use it in GitHub Desktop.
An easy way to build a custom sequence of callable operations using dot notation.
This file contains hidden or 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 DotSequence(seq) { | |
var self = this; | |
seq = seq || []; | |
self.commands = {}; | |
self.addCommand = function (name,operation) { | |
self.commands[name] = operation; | |
self[name] = function (...params) { | |
seq.push({ | |
command: name, | |
params | |
}); | |
return self; | |
}; | |
return self; | |
}; | |
self.addCommand("wait",function(){ | |
//Hard coded in 'end' function | |
}); | |
self.end = function () { | |
function execute(index) { | |
if (index < seq.length) { | |
var element = seq[index]; | |
if (element.command == "wait") { | |
setTimeout(function () { | |
execute(index + 1); | |
}, element.params[0]); | |
} else { | |
self.commands[element.command](...element.params); | |
execute(index + 1); | |
} | |
} else { | |
console.log("( Sequence Completed )"); | |
} | |
} | |
execute(0); | |
}; | |
} | |
/* | |
// Sequence like so: | |
var s = new DotSequence() | |
.addCommand("log", function (message){ // create a command | |
console.log(message); | |
}) | |
.log("Hello world") | |
.wait(3000) | |
.log("Hello world... 3 seconds later") | |
.wait(4000) | |
.log("Goodbye world") | |
.end(); | |
// Call single operations like so: | |
s.log("Hi there"); | |
// Note 'wait' will only work when used in a sequence followed by 'end' | |
s.wait(1000).log('done waiting').end(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment