sideshowcoder / canned

Server to respond with fake API responses, by using a directory of files for finding out what to say!
213 stars 46 forks source link

Fix up regex, fails test for #79(!) #94

Open wadtech opened 8 years ago

wadtech commented 8 years ago

This change fixes a couple of problems:

The regexes as they stood were both matching per character, which makes for some interesting matches such as: http://rubular.com/r/uZpZRyhmpN

Changing the character group to a non-captured OR group makes the results: http://rubular.com/r/XBXkjlu54P

It also removes the /g option from the regexp. Since the .exec method is called only once per line it was causing weird results because /g causes it to return falsy unexpectedly. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#Finding_successive_matches)

wadtech commented 8 years ago

I've pushed a quick refactor to clear up the responsibility of some of the line parsing code. Unfortunately my original change breaks the spec for #79 but I'm not sure why yet.

sideshowcoder commented 8 years ago

Really like where this is going :+1:

sideshowcoder commented 8 years ago

Ok so for the regex the problem is indeed that /g does not behave as expected... the fix for that would be something like

var string = "aaacaaa\naaa\nbbb\nccc\nbaaabaaa"

var re = new RegExp(/aaa/g)

var res = string.split("\n").reduce(function(acc, el) {
  el.replace(re, function(match, _index, full){
    acc.push({ match: match, full: full })
  });
  return acc
}, [])

console.log(res)

// => [ { match: 'aaa', full: 'aaacaaa' }, { match: 'aaa', full: 'aaacaaa' },
//      { match: 'aaa', full: 'aaa' }, { match: 'aaa', full: 'baaabaaa' },
//      { match: 'aaa', full: 'baaabaaa' } ]

This now works correctly with the /g as one would expect, the match set contains { match: 'aaa', full: 'aaa' }

wadtech commented 8 years ago

I pushed another big commit. I moved the request params and return options parsing into their own modules that are ludicrously similar.

Probably best to have a shared parser that deals with all the front matter (to steal a term from jekyll) and it can return the comprehensive list of options per entry in the file.

Hopefully I'm barking up the right tree. It's very much WIP, but I'd like to hear your feedback.

sideshowcoder commented 8 years ago

NICE! I really like the approach, left some comments but mostly style, I try to keep this consistent if possible. Also I think the api would be nicer if the request and response parser would basically work like this

var parseRequest = require("./request_parser")

var options = parseRequset(lines)