3

I'm just doing some research into Typeahead.js and it's a really cool library. I've managed to get a basic example working with thanks to the documentation which is also very good.

However I'm trying to get my head around what the following block of code is actually doing?

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        matches.push(str);
      }
    });

    cb(matches);
  };
};

In the example it's passed in when initialising the typeahead as the source option. I can understand that it's taking the input from the textbox and comparing it to the dataset but I'm a little confused as to what q and cb are?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Javacadabra
  • 5,578
  • 15
  • 84
  • 152

1 Answers1

5

q is the value to be searched for. This is passed into the regex matcher, and the search is case-insensitivie (the "i" param)

cb is the callback function which returns the matches found from the search.

findMatches is basically an anonymous function that is used as the implementation of the substringMatcher function.

Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115
  • Ok, that makes sense, is there a reason why the author went with an anonymous function in this case? – Javacadabra Nov 24 '15 at 17:19
  • Looks like this is kind of like a form of currying where strs is a list of strings held in a closure. Basically a convienient way of filtering strs by q – Jonathan.Brink Nov 24 '15 at 17:25
  • Ok well appreciate your help on this, makes things a lot clearer! I hate not understanding what each line is doing – Javacadabra Nov 24 '15 at 17:26
  • There is an issue in that if the passed in object (strs) changes after the typeahead object gets initialized, those changes are not visible to substringMatcher because it is copied during the initialization. Does anyone know how to reinitialize the typeahead object? I worked around this by using the name of the global object inside of the findMatches function - but if you have multiple typeahead input fields, you need a custom substringMatcher for each one. – user1279887 May 02 '17 at 15:45