swang / markovchain

generates a markov chain of words based on input files
50 stars 8 forks source link

Fix single word sentences if string is passed to .end() #3

Closed bubens closed 9 years ago

swang commented 9 years ago

Sorry for the late reply; can you explain why you are changing signs for the end function? Not sure about the reasoning but it kinda changes how it works when you do that.

bubens commented 9 years ago

I try: The problem I stumbled upon is the following: if you pass a String to .end() the generator will always finish after the first word. As far as I can tell this is due to the comparison that I changed in my pull request. I think it has something to do with the change of the API you explain in the README:

Passing a Function into end has changed a little bit, before the markov chain would continue until the Function passed returned false, now the Function being passed into end() should only return true when you want the markov chain generator to stop generating the sentence.

The .end() function itself creates a .endFn() function depending on the type of the argument passed to .end(). If the argument is a string the following function is created (index.js:169-172):

else if (endType === 'string') {
    this.endFn = function() {
      return this.sentence.split(' ').slice(-1)[0] !== fnStrOrNum
    }

The created function looks at the last word, checks if it's the same as the fnStrOrNum (that is the word at which the generator should stop generating the sentence) and returns the inverted result. This means if the last word in the sentence is not the word you look for, it will return true and the generator will stop generating the sentence.

If you change the comparison as I did in my pull request, the .endFn() will only return true (and therefore end the generator) if fnStrOrNum is equal to the last word.

I did it in my fork and it works perfectly.

swang commented 9 years ago

Merged in as a377910

swang commented 9 years ago

Thanks!