Last active
February 28, 2017 20:34
-
-
Save libetl/56763f55cf1d1ac7a01eb6476559eb69 to your computer and use it in GitHub Desktop.
pipeline
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 pipeline = { | |
mapping: {}, | |
respond: (regex, func) => { | |
this.mapping = this.mapping || {} | |
this.mapping[regex.source] = func | |
}, | |
hear: (regex, func) => { | |
this.mapping = this.mapping || {} | |
this.mapping[regex.source] = func | |
}, | |
innerRegex: /\s+/g, | |
buildAnswer: (prefixes) => { | |
const innerRegex = `(${Object.keys(this.mapping).join('|')})(?:[\s;]+|$)` | |
const globalRegex = `(${prefixes})\\s+((?:${innerRegex})+)` | |
return (robot) => robot.respond(new RegExp(globalRegex), (res) => { | |
const readOneCommand = (command) => { | |
for (const oneMappingEntry of Object.keys(this.mapping)) { | |
if (new RegExp(oneMappingEntry).test(command[1])) { | |
return this.mapping[oneMappingEntry] | |
} | |
} | |
return () => { | |
} | |
} | |
const instruction = res.match[3] | |
const theRegex = new RegExp(innerRegex, 'g') | |
let command = theRegex.exec(instruction) | |
let promise = Promise.resolve(res) | |
while (command) { | |
const thisMatch = command | |
const func = readOneCommand(command) | |
promise = promise.then(() => new Promise((resolve) => { | |
const thisRes = Object.assign(Object.create(res), res); | |
thisRes.match = thisMatch | |
func(robot, thisRes, resolve) | |
})) | |
command = theRegex.exec(instruction) | |
} | |
return promise | |
}) | |
} | |
} | |
pipeline.respond(/hello(?: again)?/i, (robot, res, resolve) => {res.respond('hello'); resolve();}) | |
pipeline.respond(/how are you/i, (robot, res, resolve) => {res.respond('fine and you'); resolve();}) | |
module.exports = pipeline.buildAnswer('(my-commands)') | |
//Example : my-commands hello; how are you; hello again |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment