Skip to content

Instantly share code, notes, and snippets.

@libetl
Last active February 28, 2017 20:34
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 libetl/56763f55cf1d1ac7a01eb6476559eb69 to your computer and use it in GitHub Desktop.
Save libetl/56763f55cf1d1ac7a01eb6476559eb69 to your computer and use it in GitHub Desktop.
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