Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
pipeline
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